Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Setting the text property of GuiText

Discussion in 'Scripting' started by Premier2k, Apr 8, 2015.

  1. Premier2k

    Premier2k

    Joined:
    Feb 27, 2014
    Posts:
    5
    Hi all,

    I've recently come back to Unity and discovered Unity 5. I'm picking my way around realising just how much I've forgotten or has changed.

    I really stuck on one change, I've tried googling and searching the forums but nothing seems to work.
    I tried to update the text property of some guitext I've placed in the scene (which for the purposes of the forum is called "health". I've called the guitext.text property and tried to set it and got told it had been deprecated and to use
    GetComponent<GUIText>() instead. (UnityUpgradable)

    I can't get my head around this at all. I think I've forgotten more than I originally thought.
    How do I access the GUIText property now?

    I've had a google around but every answer I come across seems to be the "old" way of doing things, or maybe I'm just not understanding it?

    Thanks in advance,
    Premier2k
     
  2. Premier2k

    Premier2k

    Joined:
    Feb 27, 2014
    Posts:
    5
    Just figured it out!
    For anyone else having the same issue a code snippet is below.
    I'm assuming that the public variable has to be the same name as the object you want? Or how would it know which text to find?

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using System.Collections;
    5. public class Health : MonoBehaviour {
    6. public Text healthText;
    7. float health = 100.0f;
    8. // Use this for initialization
    9. void Start () {
    10.  
    11. }
    12.  
    13. // Update is called once per frame
    14. void Update () {
    15. healthText = GetComponent<Text> ();
    16. healthText.text = "test";
    17. }
    18. }
    19.  
     
  3. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    No, you have to drag the object into the inspector. It is sufficient to use healthText.text then. Your way works as well, but it assumes the Text is part of the object the script is attached to.
     
  4. Premier2k

    Premier2k

    Joined:
    Feb 27, 2014
    Posts:
    5
    ok, I'm probably being really stupid here but I don't understand what you mean? I dragged the GUIText on to the scene and it appeared in my Hierarchy under Canvas, and then I renamed it healthText.

    Hopefully there is a pic uploaded showing what I have...
     

    Attached Files:

  5. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    You see on the right where it says: None(Text)?

    Drag the text object in there.