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

7
我有一个Unity项目,其中包含一个文本字段,我想通过点击按钮将其更改为其他内容,类似于JavaScript中的ID。有人可以帮助我吗?

2
yourText.text = "XYZ"; ? - derHugo
2个回答

11
在Unity中,您采用组件导向的设计。Text和Button只是GameObject实体的组件。游戏脚本的大部分也是作为组件附加到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.

你的脚本将是这样的:

    using UnityEngine;
    using UnityEngine.UI;

    public class ExampleScript : MonoBehaviour
    {
        [SerializeField] 
        private Text _title;

        public void OnButtonClick()
        {
            _title.text = "Your new text is here";
        }
    }

您的场景应该看起来像这样。请注意突出显示的“Title”引用。 您只需要将标题游戏对象拖放到此处即可。

a

选择您的按钮,分配一个包含脚本的游戏对象,并选择需要调用的公共方法

a

欢迎使用Unity并愉快地编码!


哇!这正是我所需要的!非常感谢你。 - Human Friend

8

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";
    }
}

你必须真正地等待才能发表评论。这是对被接受答案的一小部分进行修改,但本身并不是一个答案。 - Gert Arnold
是的,尽管我的声望太低无法评论,但我也认为查看此答案的人需要知道。你介意替我评论一下这个答案吗(带或不带署名)?还是最好将其删除并在有能力时进行评论?谢谢。 - shodev
2
截至2022年,这个答案对我来说是最好的。我遇到了将Text游戏对象分配给插槽时出现类型不匹配的问题。这是因为现在Unity似乎不再使用Text类型,而是使用TMP_Text。 - Yaume

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接