- Home /
Problem accessing variable for each child
I'm trying to run through each child of a parent object and check if a variable is true.
I have this:
for(var child : Transform in transform){
if(child.gameObject.isGoalNode){
//do stuff
}
}
isGoalNode is a variable in the script attached to each child individually. If I print the child.gameObject.isGoalNode, I get null.
I've also tried it through GetComponent:
for(var child : Transform in transform){
var childScript = GetComponent(RepairMiniGame);
print(childScript.isGoalNode);
if(child.gameObject.isGoalNode){
//do stuff
}
}
Which turns up a NullReferenceException.
I'm sure I'm just missing something in the logic, so I thought someone here might know what I'm doing wrong.
Thank you!
Answer by T27M · Nov 24, 2012 at 10:06 PM
You are accessing the component but you are not using it.
var someScript : ExampleScript; // Declare your type
someScript = GetComponent (ExampleScript); // Get the component
someScript.DoSomething (); // Access a variable in that component
If you use GetComponent() it will look for the component attached to the GameObject you are calling it from. Which is not what you want.
In your case it would be something like:
for ( var i = 0; i < number of children here; i++ )
{
var childScript = gameObject.transform.GetChild(i).GetComponent(RepairMiniGame);
if ( childScript.isGoalNode )
{
Debug.Log( childScript.gameObject.name );
//Do Something
}
}
Where i is the index of the current loop and i < 3 if you have 3 child objects. Remember your first child is at index 0.
Edit: While I was whiping this up quickly I failed noticed that the order wasn't determined by the hierarchy. This shouldn't be a problem if you are just looping through them all.
*Edit: Remember isGoalNode has to be a public bool to access it.
Hope this helps.
I was still getting nullreferenceexception when I changed to this, but that's because I had a child to the object that wasn't one with that script on it.
Once I took that out your example worked. Thank you :)
Your answer
Follow this Question
Related Questions
Accessing a variable within a function.... GetComponent() 2 Answers
GetComponent with variable script possible? 1 Answer
How can i change the scriptable object variable in child script (if it's possible) 0 Answers
How to get all children gameobjects 5 Answers
GetComponent from string name? 3 Answers