【问题标题】:Child calling a parent function that uses child's function in Unity子调用在 Unity 中使用子函数的父函数
【发布时间】:2018-03-18 18:33:31
【问题描述】:

我有一个基类,它有一个不知道它调用的函数会做什么的函数。这种行为是在孩子身上定义的。然后从孩子调用父母函数。使这项工作的正确语法/方法是什么?特别是我必须放什么而不是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 函数来自统一,每帧调用一次。如果我可以进一步澄清我的问题,请告诉我,我会尽快这样做。我不知道这是引用覆盖、接口还是抽象,所以我已经标记了它们。我会尽快解决这个问题。

【问题讨论】:

标签: c# inheritance unity3d overriding abstraction


【解决方案1】:

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

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

【讨论】:

  • 您可以将 Update() 函数移动到 ToolScript 类中。这样您就不需要为每个子类输入它。从那里调用 isActive(),它会调用子类中相关的 Use() 函数。
猜你喜欢
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多