Author Topic: Changing label text dynamically  (Read 23502 times)

catacomber

  • Guest
Changing label text dynamically
« 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.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Changing label text dynamically
« Reply #1 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.

catacomber

  • Guest
Re: Changing label text dynamically
« Reply #2 on: July 28, 2012, 10:16:49 PM »
Phew! It works now.  :  )  I guess will have to learn C# on the fly.  :  )  Thank you!

jeldrez

  • Sr. Member
  • ****
  • Thank You
  • -Given: 8
  • -Receive: 4
  • Posts: 352
    • View Profile
Re: Changing label text dynamically
« Reply #3 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!
« Last Edit: March 14, 2013, 01:27:20 PM by jeldrez »

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Changing label text dynamically
« Reply #4 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.

jeldrez

  • Sr. Member
  • ****
  • Thank You
  • -Given: 8
  • -Receive: 4
  • Posts: 352
    • View Profile
Re: Changing label text dynamically
« Reply #5 on: March 14, 2013, 04:01:28 PM »
Yeah, I did that. Thanks!