Unity3d如何在代码中更改UI.Button文本 [英] Unity3d how to change UI.Button text in code

查看:3314
本文介绍了Unity3d如何在代码中更改UI.Button文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,我正在尝试制作一只飞扬的小鸟克隆,我需要显示分数的帮助.我已经添加了乐谱并将其显示在控制台上,但是我无法将其显示在gui文本上.

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.

我试图通过谷歌搜索该怎么做,并观看了很多人的飞鸟教程,以了解他们是如何做到的,但是当他们引入新的ui系统时,所有这些都在unity 4.6之前,以及他们使用的相同代码似乎不起作用.

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.

那么我该如何访问代码中附加到游戏对象上的gui文本?谢谢.

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

推荐答案

如果要为此使用4.6 UI版本.您将需要添加UnityEngine.UI;

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

C# 使用UnityEngine.UI; 的JavaScript 导入UnityEngine.UI;

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

确保您在层次结构中有一个Canvas,并在Canvas中创建一个Text Object.

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

下一步,您可以设置Text的公共字段,以便Unity中的检查器可以看到它,或者只使用GameObject.Find,我不建议这样做,因为它真的很慢.

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.


 }

}

这篇关于Unity3d如何在代码中更改UI.Button文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆