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 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:
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.

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


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 :wink: Cheers