- Home /
grab a variable off of a script of a child of an object?
Simple question really.
I found GetComponentsInChildren, but I think using this means that both the parent and the child have to have the same component? Because it doesn't work.
I am instantiating an Empty game object, who's child has a script that I need to access a variable from. I suppose I could create a very small script and attach it to the parent to pass the call down to the child, but I'd rather just get the object directly.
Is there anyway to do this?
Answer by robertbu · Apr 20, 2014 at 02:30 AM
Assuming it is a first level child, and you've named it uniquely (i.e no other child of the same name), you can do:
var child transform.Find("NameOfChild");
var someVariable = child.GetComponent(SomeScript).theVariable;
If you are going to be doing it each frame, then it is best to use Start() to cache a reference:
private var someScript : SomeScript;
function Start() {
someScript = transform.Find("NameOfChild").GetComponent(SomeScript);
}
Then you can use 'someScript.theVariable' to access this variable during the rest of the lifetime of the game object.
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
ren]er cube problem 0 Answers
Update Parent/ Children From Script? 2 Answers
Object pool with "Null Reference Exception" problem 1 Answer
create GUI.Label and then access to it.. 2 Answers