我正在尝试访问单击的按钮的文本。但它总是返回游戏对象的第一个子对象的文本。但我想访问单击的子对象的文本。
我尝试了下面的代码:
transform.gameObject.GetComponentInChildren<Button>().GetComponentInChildren<Text>().text;
您可以创建一个引用您关心的文本的自定义类:
public class ButtonExtras : MonoBehaviour
{
public Text buttonText; // assign this in the inspector
}
然后其他地方:
GetComponentInChildren<ButtonExtras>().buttonText.text = "hello!";
所以我假设您显示的代码行位于某个通用对象上的脚本中(而不是每个按钮上)。所以你可以做的就是采用一个按钮作为参数,如下所示:
void HandleText(Button button){
Text text = button.getComponentInChildren<Text>();
// do whatever you want to do with the text here
}
然后对于每个按钮,您可以将此方法添加到 OnClick 侦听器中,并将按钮本身作为参数。希望这是有道理的
我找到了一个简单的解决方案:
GameObject.Find(EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>().GetComponentInChildren<Text>().text
感谢所有分享想法的人。
此代码片段访问 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);
}
}
在最新版本的 Unity 中,您将需要使用
UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name).GetComponent<Button>().GetComponentInChildren<Text>().text