- Home /
Best way to share a variable
Hi,
Whats the best way to share and access a variable from other scripts ?
I have a script that I call GlobalVars.js and it has a list of public variables on i that I access through other scrips by using something like the sample script below, is that the best way to do it or using static variables and calling scriptName.varName ?
Thanks.
#pragma strict
private var globalVars : GameObject; // Referance to the GameObject with the GlobalVars on
function Awake(){
globalVars = GameObject.Find("Global Vars"); // Find the gameObject with the GlobalVars script attached
}
function Start(){
}
function Update(){
globalVars.GetComponent(GlobalVars).terroristHealth = 100; // Update the variable
}
Answer by hvilela · Aug 27, 2012 at 03:52 PM
Your variables in globalVars could be static, this way you can eliminate the "Global Vars" game object, the globalVars reference, and the Awake code. All you have to do is:
function Update(){
GlobalVars.terroristHealth = 100;
}
Thanks for that, is that way more optimised than the way I'm doing it ?
Your answer
![](https://koobas.hobune.stream/wayback/20220613080246im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Increase Static Var gradually 1 Answer
Should I create local copy of global variable? 3 Answers
variable doesn't change 1 Answer
Restart the game when Health variable reaches 0 4 Answers
Static variables 1 Answer