(NGUI) How to display label string from int.

Thanks for the help. I’ve been looking on C# forums and Unity and am having trouble finding an answer to this problem.

I’m trying to implement an NGUI label that displays a string defined by another script.
Here’s what I have so far.

labelChange.cs

using UnityEngine;
using System.Collections;

public class labelChange : MonoBehaviour {

   // Use this for initialization
   void Start () {
      
      UILabel lbl = GetComponent<UILabel>();
lbl.text = "";
   
   
   }
   
   // Update is called once per frame
   void Update () {
		UILabel lbl = GetComponent<UILabel>();
		lbl.text = GetComponent<resourceBox>().showCash();;
   }
	
}

resourceBox.cs

using UnityEngine;
using System.Collections;

public class resourceBox : MonoBehaviour {

	public int startCash;
	private int currentCash;
	
	// Use this for initialization
	void Start () {
		startCash = currentCash;
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	
	public string showCash () {
		return(currentCash.ToString());
	}
}

When I run this, it just shows a ‘0’ in the label, regardless of what I set startCash to.

So your problem is that you are setting startCash = currentCash, when you meant to set currentCash = startCash in Start.

A couple of points on general coding here:

  • Don’t call classes a name starting with a lower case letter - the convention is to make all types start with an uppercase and it can lead to confusion when others read your code (or you read it yourself!), lowercase first letters normally indicate a variable.

  • Don’t call GetComponent every frame, just call it in Start or Awake and cache the result

  • You don’t need the brackets around the return value.