- Home /
Script to add script to all children
Hello, I'm trying to use a script to add a script component to all of the children of the object. This script is not directly placed on the object so I'm not sure if I need to use GameObject.Find() in some cases. Below I've posted some code I've put together that doesn't work. It just keeps giving errors about the add component function. Any help would be appreciated
void Start () {
Transform[] allChildren = GetComponentsInChildren<malenude>();
femaleNude = GameObject.Find("femalenude");
femalenudeScript = femaleNude.GetComponent<FemaleNude>();
femalenudeScript.ChangeEnabled(false);
foreach (Transform child in allChildren) {
child.AddComponent(MaleNude);
maleNude = GameObject.Find(Transform);
malenudeScript = maleNude.GetComponent<MaleNude>();
malenudeScript.ChangeEnabled(false);
}
}
Answer by aldonaletto · Dec 26, 2011 at 09:54 AM
Any compiled script in your project is a valid component, and may be added with AddComponent like any other native component (Rigidbody, AudioSource etc.).
Supposing you want to add the script FemaleNude.cs to all children, you should do something like this (parent script):
void Start(){ foreach (Transform child in transform){ child.AddComponent<FemaleNude>(); } }NOTE: C# and JS can't see each other at compile time, thus if FemaleNude was a JS script, this would produce an error (kind of "FemaleNude unknown in the current context" or whatever).
If you need to add JS scripts, they must be compiled in a previous stage - see Script Compilation.
Thank you for your reply. Ok so I changed the code to what you have above. But I'm still getting an error that it can't be used as a statement
The error message reads, "Only assignment, call increment, decrement, and new object expressions can be used as a statement"
Now its saying Transform does not contain a definition for AddComponent
$$anonymous$$y fault, it should be:
child.gameObject.AddComponent<FemaleNude>();