在Unity中更改按钮文本

11

我将尝试在Unity场景打开时更改按钮的文本。我尝试了不同的方法来更改按钮的文本。

这是我的代码:

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

}

你是在尝试创建动态按钮吗? - comphonia
你期望的结果和实际表现有何不同?有什么具体没有成功的地方吗? - derHugo
它给了我这个错误:Assets/Scripts/script.cs(15,43): error CS0030: 无法将类型 UnityEngine.UI.Button' 转换为 UnityEngine.GameObject'。 - Ak Pasaf
是的,它会因为GameObject b1object = (GameObject)Instantiate(b1)出现错误。 - joel64
1个回答

14
   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的对象? - Ak Pasaf
TextMeshProUGUI类的参考不再起作用了。https://forum.unity.com/threads/textmeshprougui-class-reference-not-working-anymore.541571/ - Ak Pasaf
你有加入命名空间 using TMPro; 吗?你正在使用 TextmeshPro 对吧? - joel64
我把我的代码改成了:using UnityEngine; using UnityEngine.UI; using TMPro;public class script : MonoBehaviour {public Button b1; public TextMeshProUGUI b1text; void Start() { GameObject b1object = Instantiate(b1.gameObject); b1text = b1object.GetComponentInChildren(); btnValue(); } public void btnValue() { b1text.text = "sdfa"; }} - Ak Pasaf
让我们在聊天中继续这个讨论 - Ak Pasaf
显示剩余2条评论

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