Search code examples
c#unity-game-enginemonodevelopunity3d-gui

Unity3d how to change UI.Button text in code


Simple question, I am trying to making a flappy bird clone and I need help displaying score. I have the score being added and displayed to the console, but I cant get it to show on a gui text.

I've tried to google how to do this and watch a lot of people's flappy bird tutorials to see how they did it, but all them are before unity 4.6 when they introduced the new ui system, and the same code they use does not seem to work.

So how can I access my gui text that is attached to my game object in code? Thanks.


Solution

  • If you want the 4.6 UI version for this. You will need to add the UnityEngine.UI;

    C# using UnityEngine.UI; JavaScript import UnityEngine.UI;

    Make sure you have a Canvas in the Hierarchy and make a Text Object inside the Canvas.

    Next You can either make a public field of Text so the inspector in Unity will be able to see it or just use GameObject.Find which I do not recommend because it is really slow.

    using UnityEngine;
    using UnityEngine.UI;
    
    public class FlappyScore : MonoBehaviour{
    
    // Add the Above if you still haven't cause the Text class that you will need is in there, in UnityEngine.UI;
    
    public Text MyScore;
    
    // Go back to Unity and Drag the "text" GameObject in your canvas to this script.
    
    void Start(){
    
     /* if Having difficulty with the above instruction. Un comment this comment block.
    MyScore = GameObject.Find("text").GetComponent<Text>();
    */
    
    
      MyScore.text = "50";
     // Your score needs to be casted to a string type.
    
    
     }
    

    }