- Home /
Using variables from other script and converting them to another variable
Hello,
In my game i have about 6 areas that must be discovered by player and take photo of them, if player did this, it will play a sound and it change variable found to 1(in that GO). So what i want to do i want to count how many areas he discovered by another script and convert it to another variable called foundcount, and then i will add some other things such as how many areas he discovered on gui and stuff :)
Answer by CatDevPete · Mar 24, 2013 at 02:14 PM
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)
Answer by stevemk14ebr · Mar 24, 2013 at 02:08 PM
Method 1)you need to first make a referance to your other script, note that the gameobject must have both scripts attached
//replace vp_FPSController with your script name
Controller = gameObject.GetComponent<vp_FPSController>();
then you can simply do
Controller.found=1;
replace found with the public variable you are trying to change from the other script.
Method 2) if the script is not on the same gameobject you still need to referance it so make a variable with a referance then drag that game object onto the variable in the inspector
//MUST CHANGE THE vp_FPSController to the name of the
//script you are trying to get the variable from
public vp_FPSController controller;
then you can change the variable in the same way
//variable found must be public
vp_FPSController.found=1;
3) if when you make that variable public you don't want it show in the inspector you can put
[HideInInspector]
above it