首页 > 解决方案 > 使用接口来利用基本的 Unity 方法?

问题描述

我的想法是删除仅因为我需要执行一次性任务而存在的 Monobehavior 脚本,例如在他们的“开始”方法中分配一个事件或初始化一个对象,..

可以使用基本方法(Awake、Start、..)创建接口并从我唯一的 Monobehavior 中调用所有对象吗?

这是我的完整示例:

public interface IMain {

    void OnMyAwake();
    void OnMyStart();
    void OnMyUpdate();
}


private void Awake()
{
    Debug.Log("I'm awake");

    for (int x = 0; x < list.Length; x++) {

        list[x].OnMyAwake();

    }
}


// Use this for initialization
void Start () {

    Debug.Log("I'm Start");

    for (int x = 0; x < list.Length; x++)
    {

        list[x].OnMyStart();

    }

}

// Update is called once per frame
void Update () {

    for (int x = 0; x < list.Length; x++)
    {

        list[x].OnMyUpdate();

    }
}

对这种方法的想法?

标签: c#unity3d

解决方案


您需要确保在所有定义Awake()之前不能调用,或者包含一些东西来正确处理这种情况list[0..n-1]

一旦处理好,这应该可以按您的预期工作(时间方面)。

您可能还想包含OnDestroyOnDisable方法。


推荐阅读