Unity:非monobehavior类可以初始化monobehavior对象列表吗?

时间:2018-03-19 23:26:52

标签: list class object unity3d initialization

我在初始化非monobehavior类中的monobehavior对象列表时遇到了问题。我想知道这是不是可以做的事情,或者我的问题是否在其他地方。感谢。

2 个答案:

答案 0 :(得分:0)

正如@Galandil评论的那样,如果没有尝试代码,或者至少有更好的解释,很难知道解决方案。

由于缺少详细信息:是的,您可以在不继承MonoBehaviour的C#类上初始化MonoBehaviours列表。

using UnityEngine; // It is imperative to include this namespace if you don't want to use dot notation.
using System.Collections.Generic;

/// If you give this attribute to a class, the Editor will try to serialize it on the inspector.
//But for that, it should be an attribute from either a MonoBehaviour or a ScriptableObject.
[System.Serializable]
public class Holder
{
    private List<MonoBehaviour> _monos;

    public List<MonoBehaviour> monos
    {
        get
        {
            if(_monos != null) _monos = new List<MonoBehaviour>();
            return _monos;
        }
    }
}

但是需要更多的细节,就像一个理由一样,为什么在一个类上有一个MonoBehaviours列表,如果没有在GameObject实体上引用的话,它必然是持久的?例如,为什么不使用ScriptableObjects?为什么不坚持使用具有上述List的MonoBehaviour脚本的Empty GameObject实体?

答案 1 :(得分:0)

你不能为MonoBehaviour使用显式构造函数。我是。

myMono= new MyMonoClass() ; // will not work

相反,要求团结通过AddComponent创建它们,这是有意义的,因为Unity的组件系统非常需要知道每个单独,如果你可以创建它们,它们将没有变换,它们不会有回调,它们不会有更新,他们的协同程序将无法正常工作。

你可能想要将它们全部放在一个对象上,可能是多个,也许你需要先生成游戏对象,幸运的是你可以用通常的方式创建它们,所以你可以做一些像

myMonoList.Add(new GameObject().AddComponent<MyMonoClass>());

您还可以复制(实例化)现有对象