- Home /
How can I reference a float variable to a GUI label in another script?
(C#)I have looked through a lot of other posts on here and none of them relate to GUI Labels like mine does. So, what I am trying to do is, I have a variable in one script that has a value of whatever, say 4, then I want to transfer that variable/value to another script where it hold my GUI Label to show that value. The code is below. Script 1:
public float newsPapersSold;
// Use this for initialization
void Start () {
newsPapersSold = 0;
}
// Update is called once per frame
void Update () {
}
public void NPClick()
{
newsPapersSold ++;
Debug.Log("NP: " + newsPapersSold);
}
}
Script 2:
public float newspapersSold;
public GUIStyle npSoldGUI;
public Button newspaperBtn;
// Use this for initialization
void Start()
{
newspapersSold = GetComponent<SellNewsPaper>().newsPapersSold;
}
// Update is called once per frame
void Update()
{
}
public void OnGUI()
{
GUI.Label(new Rect(480, -25, 800, 200), "Newspapers Sold: " + newspapersSold, npSoldGUI);
}
}
Answer by game4444 · Nov 20, 2018 at 05:05 AM
You have two solution for this problem. You have to make public GameObject in your class where you need that float variable and get that variable in this class for Example.. public GameObject NewsPaperSoldObject; public float newspapersSold; void Start() { newspapersSold = NewsPaperSoldObject.GetComponent().newsPapersSold; } // then you could use this. 2nd Solution is you could make your newsPaperSold float to public static float newsPaperSold; then you could access this variable in any class with you class object. like Class.newsPaperSold;
@game4444 So, this stopped the error from showing, but now the variable is changing and I can see it in the inspector, but the variables value is not making its way to the other UI panel. If you know what this problem could be then that would be great!
I mean basically I have a UI panel for the button that contains the variable and I have a UI panel that displays a GUI Label of the variable.
Your answer
Follow this Question
Related Questions
Reference specific variable from a specific gameObject? 2 Answers
Getting a variable from a specific gameobject for another script 3 Answers
Referencing AND affecting a variable from another script 1 Answer
Properly referencing a variable from another script 1 Answer
How to share a variable through multiple copys of the same script 2 Answers