How do you access child objects with a tag?
Suppose we have a car (the parent) consisting of children–a car body, tire01, tire02, tire03, tire04.
The tires are all tagged “tire” and a script named “tire control” is attached to them. I want to assign a same value to these tires. I tried the following code but it didn’t work.
var tires : GameObject[] = GameObject.FindGameObjectsWithTag("tire");
for(var aTire : GameObject in tires)
{
aTire.GetComponent("tire control").punctured = true;
}
It seems me that GameObject.FindGameObjectsWithTag() function doesn’t work for child objects. Am I correct, and what is the right way to access them?
There are a few ways to get to the children. But you could also trigger them with a static var.(ie)
//main scipt
static var mainScript : boolean;
//tire script
if(mainScriptName.mianScript==true){
//myTires are flat so run to da chopper
}
That way you dont need to use tags. But if like tags.
You could try.
for (var child : Transform in transform) {
if(child.tag==tire01) {
child.GetComponent(tireControl).punctured = true;
}
//this works if your talking from the parent script
Both approaches are good, although I prefer not to use global variables. A related question is: Is there a single call, using perhaps looping or an array, instead of this working but ridiculous code?