- Home /
Transfer values from one script to another
Hi Guys, this question has been asked many times but I can't seem to find one exactly like my scenario.
I have 3 Scripts, in the Hierarchy, they are each under one another like so:
ScriptA
ScriptB
ScriptC
ScriptA has the value I wish to give to ScriptC.
It's important to note that "STATIC" is not an option.
So far, I've worked out that I can get a value from B to C, by using on scriptC: varX = transform.parent.GetComponent(ScriptB).varY;
But using this same method from A to B results in the following error: NullReferenceException EnemyBodyScript.Update () (at Assets/Scripts/ScriptB.js:27)
I've also tried with root instead of parent, which resulted: NullReferenceException: Object reference not set to an instance of an object ScriptB.Update () (at Assets/Scripts/ScriptB.js:27)
If anyone could help I would be very grateful.
Stupid question but are you using the appropriate script name as parameter? Just in case.
Hi fafase, I'm just inspecting that link you gave a moment ago. and yep I'm using the appropriate script name in the parameter.
I'm guessing the object your trying to access is empty. Like..a GameObject variable will be null if you did not assign an object to it.
If I understand what your saying Aeonixion, then, no, the value is infact there. i.e. var life = 50;
Answer by Tim-Michels · Nov 30, 2012 at 08:33 AM
Your hierarchy is very important here, let's say you want to acces a value from script B inside your script A...
You can do that like this: (inside your ScriptA)
GetComponentInChildren(ScriptB); //Will work inside ScriptA
GetComponentInChildren(ScriptC); //Will also work inside ScriptA
When you want to acces a variable from script A inside your script B:
transform.parent.GetComponent(ScriptA); //Will work inside ScriptB
GetComponentInChildren(ScriptC); //Will also work inside Script
From inside your script C you can acces the other scripts like this:
transform.root.GetComponent(ScriptA); //Will work inside script C
transform.root.GetComponentInChildren(ScriptB); //Will work inside script C
or
transform.parent.GetComponent(ScriptB); //Will also work inside script C
I hope you understand what I'm doing here, basically the GetComponentInChildren is a very usefull function that can be used to get a ScriptC component, even if it's called on a ScriptA gameObject.
I hope I'm making any sense to you ;) Cheers
Thank you Tim, that was very helpful. I would have figured it out on my own HOURS ago, but as it turns out, somewhere in my script, something was making ObjectB detach itself from ObjectA. Once I resolved that, using Root to jump from ScriptC to Script A worked awesomely. Thank you very much and to everyone else for your help. I love the unity community.