- Home /
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)
Answer by wlad_s · Sep 10, 2012 at 08:55 PM
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 :) I'm no expert at scripting but that's how I do it.
Cheers.
Oh, and keep in $$anonymous$$d that the values of static vars get transferred to the next level when loaded. That's great for score and number of lives for example. But sometimes you need them to reset to initial value so you must do it in a Start function. You maybe know that already but I didn't :) so I guess it's ok to mention it should anyone else like me read this.
Static variables, in certain places, can be a very good way to go (the score and lives examples are some of the best). However, static can also have some hazards (the people who make too many static variables just to avoid learning about connecting scripts together usually regret it later).
Uberweiss's method is generally how I do it as well.
Answer by Screenhog · Sep 10, 2012 at 08:45 PM
You'll need to learn about accessing other components: http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Components.html
If this doesn't explain it well enough, I can go into more detail.