如何创建一个脚本列表,并将它们作为组件添加到一个新的游戏对象



我想创建一个脚本列表,并将它们作为组件添加到一个新的游戏对象。我想我要添加的脚本从Monobehaviour和我的基类"水果"继承。

到目前为止,我有测试代码来创建一个空对象,并尝试把两个脚本(到目前为止没有运气)

public class List_Test : MonoBehaviour {
    public List<Fruit> fruitList;

    void Start () {
        fruitList  = new List<Fruit>();
        fruitList.Add(new Pear());
        fruitList.Add(new Apple());
        foreach(Fruit fru in fruitList){
            print ("A fruit was found and it was a " + fru);
        }
        GameObject tInstance = new GameObject("test");
        for (int i = 0; i < fruitList.Count; i++){
            Fruit inst = fruitList[i];
            tInstance.AddComponent<inst>(); 
/* This doesn't work at all and throws an error in the inspector
error CS0246: The type or namespace name `inst' could not be found. Are you missing a using directive or an assembly reference? */
            print (inst);
        }
    }
}

我有一个基本的水果类

using UnityEngine;
using System.Collections;
public class Fruit {
}

然后是子类

using UnityEngine;
using System.Collections;
public class Apple : Fruit {

}

等等。

如果我尝试在基类Fruit中继承Monobehavior,则子类将不会添加到列表中。它打印

A fruit was found and it was a null
UnityEngine.MonoBehaviour:print(Object)

我似乎也在努力添加这些脚本作为组件,无论从Monobehaviour继承与否,尽管

提前感谢任何帮助或代码你可能有!

吉姆

我想你弄错了。它是这样的:

tInstance.AddComponent<inst>();

这是一个泛型方法AddComponent<T>,其中T是一个类型,而不是一个实例。例如,AddComponent<Pear>()是有效的,但AddComponent<new Pear()>()不是。

当你不知道编译类型时添加一个组件,你可以使用AddComponent(Type)。你可以这样使用:

tInstance.AddComponent(inst.GetType());

获取实例的类型并将其传递给AddComponent。Unity将创建一个具有正确类型的组件,并将其附加到tInstance

相关内容

最新更新