If you want to access variables in other scripts, there are several ways to do this.
- You can set the variable to be global, so all you need is the script and variable name.
eg. If the variable ‘foundCount’ is in script ‘TestScript’, you access it by using:
TestScript.foundCount
So, incrementing it would be:
TestScript.foundCount ++;
You can set variables to be global when declaring them by adding the ‘static’ keyword in front, like:
static var foundCount : int = 0;
- If you don’t want the variable to be global, you need to know which Game Object has the script with the variable. When you declare a gameobject variable,
var objectVariable : GameObject;
…You can either use the inspector to set the object with the script, or use:
objectVariable = Find(“GameObject_Name”);
(People will tell you that using Find() is very performance-heavy, though: http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html)
Once you got the game object, you use:
objectVariable.GetComponent(Script_Name).foundCount
…to access the variable.
- Use functions to send values then assign them in the other script.
Using functions ensures good encapsulation practices, and allows you to change and edit the variable names and types without any issues. You will still need to target the Game Object first, then use:
objectVariable.functionName()
For functions, it’s best if you read up more about it here: http://forum.unity3d.com/threads/34015-Newbie-guide-to-Unity-Javascript-(long)
how can i use variable from other script?
– riko4628