Tengku Fathullah
Tengku Fathullah

Reputation: 1370

AddComponent<> through extension method

Error: 'UnityEngine.GameObject' must be convertible to 'UnityEngine.Component'

I try to addcomponent through extension method which is non-monobehaviour class, I know it is wrong, but is there any solution to the problem?

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

from monobehaviour class I call the extension method like this

targetObject2.AddGameObject(0, 2);

basically what I want to achieve is addcomponent<> to all child through extension method.

Upvotes: 0

Views: 144

Answers (2)

Tengku Fathullah
Tengku Fathullah

Reputation: 1370

The right way to add new GameObjest as child is

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.

Upvotes: 1

Tom
Tom

Reputation: 627

GameObjects aren't components, GameObjects are the objects on which you put components on. Thats why it says that you are trying to convert a GameObject into a Component.

So do you want to add a GameObject as a child? Do you want to create a new one?

You use AddComponent to add a Component(like MeshRenderer, BoxCollider, NetworkIdentity, ...) or one of your scripts(which are also components when they derive from Monobehaviour) to an already existing gameobject.

Let's say you want to add a Prefab you made as a child. What you do is to create a new GameObject and then set its parent like :

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

Upvotes: 0

Related Questions