在统一中,如何访问作为对象子对象的按钮文本?

问题描述 投票:0回答:5

我正在尝试访问单击的按钮的文本。但它总是返回游戏对象的第一个子对象的文本。但我想访问单击的子对象的文本。

我尝试了下面的代码:

transform.gameObject.GetComponentInChildren<Button>().GetComponentInChildren<Text>().text;
c# unity-game-engine
5个回答
1
投票

您可以创建一个引用您关心的文本的自定义类:

public class ButtonExtras : MonoBehaviour
{
    public Text buttonText; // assign this in the inspector
}

然后其他地方:

GetComponentInChildren<ButtonExtras>().buttonText.text = "hello!";

0
投票

所以我假设您显示的代码行位于某个通用对象上的脚本中(而不是每个按钮上)。所以你可以做的就是采用一个按钮作为参数,如下所示:

void HandleText(Button button){
    Text text = button.getComponentInChildren<Text>();
    // do whatever you want to do with the text here
}

然后对于每个按钮,您可以将此方法添加到 OnClick 侦听器中,并将按钮本身作为参数。希望这是有道理的


0
投票

我找到了一个简单的解决方案:

GameObject.Find(EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>().GetComponentInChildren<Text>().text 

感谢所有分享想法的人。


0
投票

此代码片段访问 Button(父级)中的 TextMeshPro 组件(子级)并检索其包含的文本。

using UnityEngine.UI;
using TMPro; //add this

public class LabelToggle: MonoBehaviour {

    private void Start() {
        toggleButton = GetComponent < Button > ();
        print(toggleButton.GetComponentInChildren < TMP_Text > ().text);
    }
}

0
投票

在最新版本的 Unity 中,您将需要使用

UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>().GetComponentInChildren<Text>().text
© www.soinside.com 2019 - 2024. All rights reserved.