Have 1 Global Variable With 1 True Value
Hello. I have multiple scripts within my game, and they are all accessing a single variable, a public money.
public float money;
The problem is that when I try to access this variable in other scripts, i.e:
GameObject dismaster = GameObject.Find("Master");
moneyComp = dismaster.GetComponent<GlobalMoney>();
dismoney = moneyComp.money;
It essentially creates a new variable in each script that has the same value as this global value is when it is assigned. It is reading said variable, but I need it to share the variable, and write back to this master. I suppose I could manually do it, but that seems extremely complex. Any ideas?
Answer by EmHuynh · Feb 17, 2016 at 07:24 AM
Hello, @UnityAlexV.
You can create a public function in GlobalMoney.cs
script that can change the value of the float variable, money
. Then call it from the other script.
In GlobalMoney.cs:
public void SetMoneyMethod( float amount ) {
money = amount;
}
In the other script:
void Update()
{
if( Input.GetKeyUp( KeyCode.Space ) ) {
SetMoneyMethod( 2016 );
Debug.Log( moneyComp.money );
}
}
Or set it directly.
In the other script:
void Update()
{
if( Input.GetKeyUp( KeyCode.Space ) ) {
moneyComp.money = 1337;
}
}
Your answer
Follow this Question
Related Questions
Determine Which Switch Case Was Called Last C# 1 Answer
public vs private array in classes 0 Answers
Unity 4.1.5 is not showing certain public variables in the inspector 1 Answer
How to Reference Other Scripts' Variables in C# 1 Answer
My C# script crashes Unity and I don't know why, help? 0 Answers