【问题标题】:Change text of Button in Unity在 Unity 中更改按钮的文本
【发布时间】:2018-10-29 20:28:41
【问题描述】:

我试图在 Unity 中打开场景时更改 Button 的文本。我尝试了不同的方法来更改 Button 的文本。

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class script : MonoBehaviour {

    public Button b1;
    public TMP_Text b1text;


    void Start()
    {
        GameObject b1object = (GameObject)Instantiate(b1);
        b1text = b1object.GetComponentInChildren<TMP_Text>(true);
        btnValue();
    }

    public void btnValue()
    {
        b1text.text = "sdfa";
    }

}

【问题讨论】:

  • 您要创建动态按钮吗?
  • 究竟是什么不工作/行为与您的预期不同?
  • 它给了我这个错误:Assets/Scripts/script.cs(15,43): error CS0030: Cannot convert type UnityEngine.UI.Button' to UnityEngine.GameObject'
  • 是的,它会因为 GameObject b1object = (GameObject)Instantiate(b1); 而出现该错误;

标签: c# unity3d button


【解决方案1】:
   public Button b1;
public TextMeshProUGUI b1text;


void Start()
{
    b1text = b1.GetComponentInChildren<TextMeshProUGUI>();
    btnValue();
}

public void btnValue()
{
    b1text.text = "sdfa";
}

或者你可以创建一个

public TextMeshProUGUI txt;

在检查器中拖动 textmeshpro 文本并更改文本。

    txt.text = "sdfa";

【讨论】:

  • 你为 b1object 使用了什么?
  • TextMeshProUGUI 类引用不再起作用。forum.unity.com/threads/…
  • 你把命名空间.使用 TMPro; ?您使用的是 textmeshPro 对吗?
  • 是的,我放置了命名空间,并且正在使用 Textmeshpro for android。
  • 我想更改按钮的文字。
猜你喜欢
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多