错误:“UnityEngine.GameObject”必须可转换为“UnityEngine.Component”
我试图通过非单行为类的扩展方法添加组件,我知道它是错误的,但是有什么解决方案吗?
public static void AddGameObject(this Transform go, int currentDepth, int depth)
{
if (depth == currentDepth)
{
GameObject test = go.gameObject.AddComponent<GameObject>(); //error is here
Debug.Log(go.name + " : " + currentDepth);
}
foreach (Transform child in go.transform)
{
child.AddGameObject(currentDepth + 1, depth);
}
}在单行为类中,我调用这样的扩展方法
2.(0,2);
基本上,我想要实现的是通过扩展方法对所有子类进行addcomponent<>。
发布于 2015-11-26 05:51:35
GameObjects不是组件,GameObjects是放置组件的对象。这就是为什么它说要将一个GameObject转换成一个组件。
那么,您想要添加一个GameObject作为一个子吗?你想要创建一个新的吗?
使用AddComponent添加组件(如MeshRenderer、BoxCollider、NetworkIdentity、.)或者您的脚本之一(它们也是从Monobehaviour派生出来的组件)到已经存在的游戏对象。
假设你想添加一个你小时候做的预制件。您要做的是创建一个新的GameObject,然后设置它的父级如下:
void AddChildGameObject(this GameObject go, GameObject childPrefab) {
GameObject newChild = Instantiate(childPrefab) as GameObject;
newChild.transform.parent = go.transform;
}发布于 2015-11-26 06:34:26
将新GameObjest作为子级添加的正确方法是
public static void AddGameObject(this Transform go, int currentDepth, int depth)
{
if (depth == currentDepth)
{
GameObject newChild = new GameObject("PRIMARY");
newChild.transform.SetParent(go.transform);
Debug.Log(go.name + " : " + currentDepth);
}
foreach (Transform child in go.transform)
{
child.AddGameObject(currentDepth + 1, depth);
}
}基本上,代码所做的是根据深度将新的GameObject作为子gameObject添加到gameObject的所有子程序中。
https://stackoverflow.com/questions/33930641
复制相似问题