在 Unity 中,当您创建一个新的 MonoBehaviour 类时,它会附带一整套您可以轻松 Hook 的函数 - 例如 Update()、FixedUpdate() 和 Awake()。我正在制作我自己的组件实体系统,我正在尝试添加一系列可以很容易地被我创建的组件 Hook 的功能。我已经将我的基类抽象化,并将 Update 和 Draw 作为可以继承的抽象函数。这工作正常,除了我的所有组件必须实现所有这些功能之外; Initialize 之类的东西对某些组件有用,但对其他组件没有用,我不确定如何模拟这种行为。
是用反射完成的吗?
请您参考如下方法:
您可以将它们定义为虚拟,并仅在必要时覆盖,而不是将您的方法定义为抽象。
class BaseComponent : MonoBehaviour
{
public virtual void OnAwesomeEvent()
{
// do nothing or implement default behaviour
}
}
class ShinyComponent : BaseComponent
{
public override void OnAwesomeEvent()
{
Debug.Log("I've been waiting for this!");
// If you need the default implementation you can call it with
// base.OnAwesomeEvent()
}
}
class LazyComponent : BaseComponent
{
// I do nothing and no one cares
}
