Unity3d how to change UI.Button text in code

痞子三分冷 提交于 2019-12-11 10:37:29

问题


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.


回答1:


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.


 }

}



来源:https://stackoverflow.com/questions/29167172/unity3d-how-to-change-ui-button-text-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!