我有一个Unity项目,其中包含一个文本字段,我想通过点击按钮将其更改为其他内容,类似于JavaScript中的ID。有人可以帮助我吗?
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”引用。 您只需要将标题游戏对象拖放到此处即可。
选择您的按钮,分配一个包含脚本的游戏对象,并选择需要调用的公共方法
欢迎使用Unity并愉快地编码!
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";
}
}
yourText.text = "XYZ";
? - derHugo