Iva*_*nov 12
在 Unity 中,您拥有面向组件的设计。文本和按钮只是游戏对象实体的组件。游戏脚本的大部分部分也是附加到 GameObject 的组件。这是当你来自 JS 时需要意识到的一个核心概念。
简而言之,要通过单击您需要的按钮来更改文本:
1) Create a GameObject with a Text component;
2) Create a GameObject with a Button component;
3) Create a GameObject with a component of your custom script;
4) Create the reference in your custom script on the Text component you want to update;
5) Create a public method in your custom script that will be invoked when you click Button;
6) Assign that method invocation to the OnClick button event through Unity inspector.
Run Code Online (Sandbox Code Playgroud)
你的脚本将如下所示:
using UnityEngine;
using UnityEngine.UI;
public class ExampleScript : MonoBehaviour
{
[SerializeField]
private Text _title;
public void OnButtonClick()
{
_title.text = "Your new text is here";
}
}
Run Code Online (Sandbox Code Playgroud)
你的场景应该是这样的。请注意突出显示的标题参考。您只需将标题游戏对象拖放到此处即可。
选择您的按钮,使用您的脚本分配一个 GameObject 并选择需要调用的公共方法
欢迎使用 Unity,祝您编码愉快!
小智 9
Unity 最近在 2021.3 版本中添加了TextMeshPro作为显示文本的方式。这个过程大致相同,但唯一的区别是包含“using TMPro”(而不是UnityEngine.UI)和“TMP_Text”(而不是“Text”)。更新后的代码看起来像这样:
using UnityEngine;
using TMPro;
public class ExampleScript : MonoBehaviour
{
[SerializeField]
private TMP_Text _title;
public void OnButtonClick()
{
_title.text = "Your new text is here";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57219 次 |
| 最近记录: |