How to Reference Other Scripts' Variables in C#
Ok mods... before you delete this, hear me out.
I have looked for a solution to this. And I looked again. And I know there are many answers. And there are even more answers.
But every answer I have found does nothing to help.
I have a script:
using UnityEngine;
using System.Collections;
public class GlobalMoney : MonoBehaviour {
public float money;
}
...and I need (well obviously not need, but want) to access the money variable in another script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MoneyDisplay : MonoBehaviour {
GameObject dismaster = GameObject.Find("Master");
GlobalMoney moneycomp = dismaster.GetComponent<GlobalMoney>();
float dismoney = moneycomp.money;
public Text TextComponent;
void Update () {
TextComponent.text = "$" + dismoney;
}
}
I get this error:
Assets/MoneyDisplay.cs(8,33): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `MoneyDisplay.dismaster'
..and this one:
Assets/MoneyDisplay.cs(9,26): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `MoneyDisplay.moneycomp'
Any help will be appreciated. If I have come off as rude, I apologize sincerely, but I am quite frustrated as I have been looking and looking for a few hours how to do such a simple task, to no avail.
Answer by EmHuynh · Feb 16, 2016 at 04:10 AM
Hello, @UnityAlexV.
To resolve the errors, try initializing dismaster
, moneycomp
and dismoney
through the Start or Awake functions, whichever suits the purpose of your script. Here's the fixed version of MoneyDisplay.cs:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MoneyDisplay : MonoBehaviour {
GameObject dismaster;
GlobalMoney moneycomp;
float dismoney;
public Text TextComponent;
void Start() {
dismaster = GameObject.Find("Master");
dismoney = moneycomp.money;
moneycomp = dismaster.GetComponent<GlobalMoney>();
}
void Update () {
TextComponent.text = "$" + dismoney;
}
}
Here is a video to explain the Start and Awake functions (click this link). Let us know if you have any questions!
Thank you kindly, but I have gotten the following error: UnityException: You are not allowed to call this function when declaring a variable. $$anonymous$$ove it to the line after without a variable declaration. Said error does not have a line or space, it simply is. Help would be appreciated.
@Unity$$anonymous$$V, that's weird. I tested the script and it worked perfectly. Let's initialize dismaster
in the Start function.