How add Compontent B to all Childs with Component A (e.g. Script)

Hello,

My plan was to develop a general function that adds each ChildObject with an existing component A and another component B.
I’m not sure if it works or if there’s a better way:

public static void CallingFunktion(string goName)
{
[...]
// Adds additive-component to all childs with trigger-component
// its root, because i want all objects of that "tree"
AddToAllChilden(go.transform.root.gameObject, new A(), new B() );
[...]
}

private static void AddToAllChilden(GameObject currentObject, Component trigger, Component additive)
{
    if (currentObject.transform.childCount > 0)
    {
        // Pick each Child
        for (int i = 0; i < currentObject.transform.childCount; i++)
        {
            AddToAllChilden(currentObject.transform.GetChild(i).gameObject);
        }
    }

    // whether the object has children or not, add a B if A component is attached
    if (currentObject.GetComponent<A>() != null)
    {
        // HOW TO ADD THE B COMPONENT HERE?
    }
}

Im really thankful for any help!

You can not create components with “new” and you can’t attach existing component instances to gameobjects. Components can only be created with AddComponent. Also there’s no need to manually do a recursive search. Just use GetComponentsInChildren it searches for all components of the given type on any nested child object.

You can do all you want with a method like this:

public static void AddToAllChildren<TTrigger, TAdd>(GameObject aRoot)
{
    foreach( var t in aRoot.GetComponentsInChildren<TTrigger>())
    {
        t.gameObject.AddComponent<TAdd>();
    }
}

You would use it like this:

AddToAllChildren<MeshRenderer, MyScript>(someGameObject);

This would add the script “MyScript” to every gameobject that has a MeshRenderer and is a nested child of someGameObject.

If you want to ensure you don’t add multiple “MyScript” to the same object you can add this if statement inside the loop:

if (t.GetComponent<TAdd>() == null)
    t.gameObject.AddComponent<TAdd>();