孩子在Unity中调用使用子功能的父功能

时间:2017-10-06 21:53:42

标签: c# inheritance unity3d override abstraction

我有一个基类,它的函数不知道它调用的函数是什么。这种行为是在孩子身上定义的。然后从孩子那里调用父母的功能。使这项工作的正确语法/方法是什么?特别是我必须放的是FunctionToBeDefinedLater示例,如下所示:

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函数来自unity,每帧调用。如果我能进一步澄清我的问题,请告诉我,我会尽快澄清。我不知道这是引用覆盖,接口还是抽象,所以我已经标记了它们。我会尽快解决这个问题。

1 个答案:

答案 0 :(得分:0)

根据@Michael Curtiss指示我的内容,我已将我的代码更新为:

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();
    }
}

星星不在代码中,只是为了强调。这段代码解决了我的问题。

相关问题