如何在Unity中通过脚本更改文本

Hum*_*end 7 unity-game-engine

我有一个带有文本字段的统一项目,我想通过单击按钮将其更改为其他内容。就像 javscript id 一样。

有人能帮我吗?

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)

你的场景应该是这样的。请注意突出显示的标题参考。您只需将标题游戏对象拖放到此处即可。

A

选择您的按钮,使用您的脚本分配一个 GameObject 并选择需要调用的公共方法

A

欢迎使用 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)

  • 至于 2022 年,这个答案最适合我。由于类型不匹配,我在将文本游戏对象分配给插槽时遇到问题。这是因为现在 Unity 似乎不再使用 TMP_Text 而不是 Text 类型。 (2认同)