AddComponent<>通过扩展方法

时间:2015-11-26 04:30:56

标签: c# unity3d unity5

错误:' UnityEngine.GameObject'必须可以转换为UnityEngine.Component'

我尝试通过扩展方法添加组件,这是非monobehaviour类,我知道这是错误的,但有没有解决问题的方法?

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);
    }
}

来自monobehaviour类我称之为扩展方法

  

targetObject2.AddGameObject(0,2);

基本上我想要实现的是addcomponent&lt;&gt;通过推广方法给所有孩子。

2 个答案:

答案 0 :(得分:1)

将新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的所有子节点。

答案 1 :(得分:0)

GameObjects不是组件,GameObjects是放置组件的对象。这就是为什么它说你试图将GameObject转换为Component。

那么你想在小时候添加一个GameObject吗?你想创建一个新的吗?

使用AddComponent将一个Component(如MeshRenderer,BoxCollider,NetworkIdentity,...)或其中一个脚本(它们也是从Monobehaviour派生的组件)添加到现有的游戏对象中。

让我们假设你要添加一个你小时候制作的预制件。你要做的是创建一个新的GameObject,然后将其父类设置为:

void AddChildGameObject(this GameObject go, GameObject childPrefab) {
    GameObject newChild = Instantiate(childPrefab) as GameObject;
    newChild.transform.parent = go.transform;
}