- Home /
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!
Answer by Bunny83 · Oct 05, 2017 at 02:14 PM
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>();
Thank you for the great and quick answer! This explanation helps me a lot :)
Your answer
Follow this Question
Related Questions
How to call the same functions both in FixedUpdate and LateUpdate? 1 Answer
Function call is not working 0 Answers
Integer Getter Method always returns zero 3 Answers
Make Script Component Do Things Even When Game Is Closed 2 Answers
Why are the components on my script disappearing when I press play 2 Answers