- Home /
How can I find a specific child gameObject with multiple instances?
During the game, a prefab gameObject "XParent" is Instantiated multiple times, each with 1 child object called "Cube",
I have added a script to the "XParent" gameObject prefab. When the player collides with "XParent", the texture of the child gameObject, "Cube" should change but I am unable to target the specific child of the prefab, because there are multiple instances of "Cube" within the game.
I can easily target a specific transform component of XParent child using...
for(var child : Transform in transform)
However, because there are multiple gameObjects called "Cube" when I use...
var xRenderer = gameObject.Find("Cube").GetComponent(Renderer);
xRenderer.material = xMaterial;
...Unity doesn't know which instance of Cube to target.
If only the following script was legal, my problem would be solved.
for(var child : GameObject in transform)
child.material = xMaterial;
I have searched on line for about 4 hours with no luck. Pleas help me target a specific child gameObject of a parent that the script is attched to.
Answer by yoyo · Jan 18, 2011 at 07:49 PM
You almost got it ... try this:
for(var child : Transform in transform)
{
child.renderer.material = xMaterial;
}
.gameObject is unnecessary. http://unity3d.com/support/documentation/ScriptReference/Component-renderer.html
Answer by Jessy · Jan 18, 2011 at 08:21 PM
If you don't have a reference to the cube, what yoyo said is fastest, unless the parent doesn't have a renderer(*). You should be aware of Transform.Find, though.
var xRenderer = transform.Find("Cube").renderer;
It wasn't necessary anyway, but don't use that form of GetComponent, that you did, anymore; it's slow. This is better:
var xRenderer = transform.Find("Cube").GetComponent.<Renderer>();
(*) In that case, use GetComponentInChildren.
Your answer
Follow this Question
Related Questions
how do I get reference to a parent or a child? 2 Answers
GameObjectWithTag Child 1 Answer
Finding Children question 3 Answers
Can I limit a .Find to the Parents and Child and not the Scene? 3 Answers
Using GameObject.Find 1 Answer