孩子调用在Unity中使用子功能的父功能
问题描述:
我有一个基类,它有一个函数,它不知道它调用的函数是什么。该行为在儿童中定义。然后从孩子那里调用父母的功能。什么是使这项工作正确的语法/方法?特别是我必须把FunctionToBeDefinedLater
例如,代替如下:孩子调用在Unity中使用子功能的父功能
public class ToolScript : MonoBehaviour {
public void isActive()
{
if (Input.GetKeyDown("space"))
{
Use();
}
}
FunctionToBeDefinedLater Use();
}
public class GunController : ToolScript
{
public void Use()
{
//Spawn bullet at this direction, this speed, give it spiral, tons of behavior etc. etc.
}
private void Update()
{
isActive();
}
}
public class FlamethrowerController : ToolScript
{
public void Use()
{
//Spawn fire at this direction, this speed, set tip of flamethrower to be red etc etc
}
private void Update()
{
isActive();
}
}
的Update
功能是从团结被称为每一帧。请让我知道,如果我可以进一步澄清我的问题,我会尽快这样做。我不知道这是否引用了重写,接口或抽象,所以我已经标记了它们。我会尽快解决这个问题。
答
基于什么@迈克尔柯蒂斯执导我我已经更新了我的代码是:
public **abstract** class ToolScript : MonoBehaviour {
public void isActive()
{
if (Input.GetKeyDown("space"))
{
Use();
}
}
**public abstract void** Use();
}
public class GunController : ToolScript
{
public **override** void Use()
{
//Spawn bullet at this direction, this speed, give it spiral, tons of behavior etc. etc.
}
private void Update()
{
isActive();
}
}
public class FlamethrowerController : ToolScript
{
public **override** void Use()
{
//Spawn fire at this direction, this speed, set tip of flamethrower to be red etc etc
}
private void Update()
{
isActive();
}
}
明星不在代码只是为了强调。这段代码解决了我的问题。
+2
您可以将Update()函数移动到ToolScript类中。这样你就不需要为每个孩子类输出它。从那里调用isActive(),它将在子类中调用相关的Use()函数。 –
阅读关于抽象和虚拟方法在这里:https://stackoverflow.com/questions/14728761/difference-between-virtual-and-abstract-methods –