Can I make a game object (Parent) that holds all or all of a type of game object and then attack a script to the Parent object and it would apply to each child or just apply to the group?
For example I want to make a chess game. Can all the chess pieces be contained in a Chess Pieces parent object and just have a mouse drag script attached to the Parent and it would work on each individual piece or is that not efficient?
asked Sep 10 '10 at 06:45 PM
attacking a script? is that like attacking the darkness? :P
The answer to the first part is that you can attach a script to a parent game object and have the script apply to either the parent and/or each child because you can loop through the children:
If you wanted to have the editor set a script on each of the children, you would do it in much the same way, but you would put the code in an editor script in stead.
The answer to the second part is that if you did it like the above loop, you can do stuff to each of the chess pieces, but it's not the best idea for something like a mouse drag. Events I believe only fire to the scripts attached to the object that fired them, therefore if you were referring to an OnMouseDrag() function or something, it would only fire for the collider of the object to which it was attached (the parent). For your specific example of the mouse drag, to do it like the above, you would have to raycast against each child individually, which can be costly and isn't really necessary as one raycast against all of them would do (put them on the same layer or something and just raycast that layer if you only want to check against them).
But this doesn't really have to be in a parent and can be anywhere (usually people put this stuff on a camera or some empty gameobject).
answered Sep 10 '10 at 09:12 PM