Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Changing text via script

Discussion in 'UGUI & TextMesh Pro' started by BusyRobot, Mar 4, 2015.

  1. BusyRobot

    BusyRobot

    Joined:
    Feb 22, 2013
    Posts:
    148
    I know this has been asked and answered a 100 times but I can't quite seem to get it, and the answers seem to be different.

    I've created some text in the scene, it's called scoreText. Now some answers on here say create a script, with public GUIText scoreText variable, then drag the text onto the variable in the inspector, but that doesn't seem to work because when I select the script to drag it on, then I select the text to drag it on, the inspector changes and there's nowhere to drag it onto.

    Another answer on here says use GetComponent to find it, but that seems to be for an object called Text? and not GUIText?

    Can someone just tell me how I can get to update my text via another script (not one attached to it), thanks!
     
  2. tranos

    tranos

    Joined:
    Feb 19, 2014
    Posts:
    180
    You could use



    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using Assets.Code.Interfaces;
    4. using UnityEngine.UI;  // necessary
    5.  
    6. Text myText;
    7.  
    8. Void Awake()
    9. {
    10.            myText = GameObject.Find("scoreText").GetComponent<Text>();
    11. }
    12.  
    13. Void Update()
    14. {
    15.          if(condition)
    16.          {
    17.                    myText.text = "Should work";
    18.          }
    19. }
    20.  
    21.  
    22.  


    Also it would be better if you add a tag to your scoreText
    and then look for it like this
    Code (CSharp):
    1. myText = GameObject.FindGameObjectWithTag("the name of your tag").GetComponent<Text>();
     
    Last edited: Mar 4, 2015
    BusyRobot likes this.
  3. BusyRobot

    BusyRobot

    Joined:
    Feb 22, 2013
    Posts:
    148
    That worked thanks, why is it Text myText rather than GuiText myText though?
     
  4. tranos

    tranos

    Joined:
    Feb 19, 2014
    Posts:
    180
    Because that is the name of the class of the new Ui.
     
  5. BusyRobot

    BusyRobot

    Joined:
    Feb 22, 2013
    Posts:
    148
    Ah, GUIText is the old version?
     
  6. tranos

    tranos

    Joined:
    Feb 19, 2014
    Posts:
    180