- Home /
Is it possible to add a script to multiple objects seleced in the inspector?
I have a castle built in Maya that is made of over 250 blocks. As I select each block, there's a script that I can add in the inspector (made by a programmer friend).
It's VERY tedious to select an object, then apply the script, then slece an object, apply the script etc.
The option for the script does NOT appear when I select the castle parent in the hierarchy.
Answer by testure · Sep 24, 2011 at 11:15 PM
A simple solution would be to put all of them inside a game object, and then write a simple script and attach it to the parent game object that does something like this:
for(int i = 0; i < gameobject.transform.GetChildCount(); i++)
{
GameObject thisObject = gameobject.transform.GetChild(i);
thisObject.AddComponent(yourScriptName);
}
now keep in mind that this does not do it via the editor- it does it at runtime, so you would need to keep the loop/addcomponent script in permanently. If you had enough objects to loop through, it could also add a minor performance hit during loading.
GetChild returns a Transform, not a GameObject. You know that you can iterate through the transform childs that way:
foreach(Transform child in gameobject.transform)
{
child.AddComponent<yourScriptName>();
}
But the general idea is right ;)
Oh, btw, you can do the same thing in an editor script, the question is whether you have enough objects so it's worth writing the script or not :D