Very simple question

I have made quite a few JS scripts in Unity, like car and AI car scripts, but I have always dodged this problem.

I declare a public var ‘firstVar’ in one script, and attach it to a gameobject ‘firstGameObject’.
I have another script on another object, and I want to say, “secondVar = firstVar from firstGameObject”.

How is that written? (In JavaScript)

If you make it a static var like: “static var firstVar: float = 1;”
then that variable will be global and the same for all the instances of that object.
Then you can reference it on any object like this: “secondVar = TheNameOFTheFirstScript.firstVar;”

If you really need it to be a public var (that is, unique for every instance of that prefab but still available from outside), then it’s a bit more complicated. You need to get the first object’s script as a component. For example, if your first object’s name is “FirstObject”, then in the script of the second object you’d have:

var myFirstObject : GameObject;

var firstObjScript : NameOfTheFirstObjectScript;

myFirstObject = GameObject.Find(“FirstObject”);

firstObjScript = myFirstObject.GetComponent(NameOfTheFirstObjectScript);

secondVar = firstObjScript.firstVar;

Of course, you don’t need to find that object by name. You can get to it anyway you want. DragAndDrop into a gameObject variable on your second object for instance.

I hope this was clear enough :slight_smile:
I’m no expert at scripting but that’s how I do it.


You’ll need to learn about accessing other components:

If this doesn’t explain it well enough, I can go into more detail.