AddComponent<> 通过扩展方法

AddComponent<> through extension method

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

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

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 class 我这样调用扩展方法

targetObject2.AddGameObject(0, 2);

基本上我想要实现的是通过扩展方法向所有 child 添加组件<>。

GameObjects 不是组件,GameObjects 是您放置组件的objects。这就是为什么它说您正在尝试将游戏对象转换为组件。

那么你想添加一个游戏对象作为 child 吗?你想创建一个新的吗?

您使用 AddComponent 将一个组件(如 MeshRenderer、BoxCollider、NetworkIdentity 等)或您的脚本之一(当它们从 Monobehaviour 派生时也是组件)添加到一个已经存在的游戏对象。

假设您要添加您制作的预制件 child。您要做的是创建一个新的 GameObject,然后将其 parent 设置为:

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

将新游戏对象添加为子对象的正确方法是

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

basically what the code does is add new GameObject as child to all childs of gameObject base on depth.