Tasharen Entertainment Forum

Support => NGUI 3 Support => Topic started by: catacomber on July 28, 2012, 10:00:13 PM

Title: Changing label text dynamically
Post by: catacomber on July 28, 2012, 10:00:13 PM
I'd like to change the text of a label dynamically and I found the script to do it in the FAQ. But wondering if you attach it to the label itself or to an empty game object.

And I get an error trying to attach it.

This is my script--the text is just test script. : )

using UnityEngine;
using System.Collections;

public class ChangeLabelText : MonoBehaviour {

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

I can't attach it to anything--get an error that the script file name doesn't match the name of the class defined in the script.
Title: Re: Changing label text dynamically
Post by: ArenMook on July 28, 2012, 10:01:19 PM
In C# your class name must match the filename where it's located. So in this case -- "ChangeLabelText" must be the name of the file where you placed the code.
Title: Re: Changing label text dynamically
Post by: catacomber on July 28, 2012, 10:16:49 PM
Phew! It works now.  :  )  I guess will have to learn C# on the fly.  :  )  Thank you!
Title: Re: Changing label text dynamically
Post by: jeldrez on March 14, 2013, 12:18:37 PM
Sorry for bringing back and old post, but I was wondering how to do this for 2 labels on the same panel, there's anyway to difference them?

using UnityEngine;
using System.Collections;

public class ChangeLabelText : MonoBehaviour {

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

I'm asking about this part:
UILabel lbl = GetComponent<UILabel>();

Thanks!
Title: Re: Changing label text dynamically
Post by: ArenMook on March 14, 2013, 03:56:05 PM
Don't use GetComponent? Reference a specific label by creating a public UILabel property on your script and setting it in the inspector.
Title: Re: Changing label text dynamically
Post by: jeldrez on March 14, 2013, 04:01:28 PM
Yeah, I did that. Thanks!