簡體   English   中英

在統一中,如何訪問作為 object 子項的按鈕文本?

[英]In unity,How can I access a buttons text that is a child of an object?

我正在嘗試訪問單擊按鈕的文本。但它總是返回 gameObject 的第一個子項的文本。但我想訪問單擊的子項的文本。

我嘗試了下面的代碼:

transform.gameObject.GetComponentInChildren<Button>().GetComponentInChildren<Text>().text;

您可以自定義 class 引用您關心的文本:

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

然后在別處:

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

因此,我假設您顯示的代碼行位於某個通用 object 上的腳本中(而不是在每個按鈕上)。 所以你可以做的是將一個按鈕作為參數,如下所示:

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

然后對於每個按鈕,您可以將此方法添加到 OnClick listernes,並將按鈕本身作為參數。 希望這是有道理的

我找到了一個簡單的解決方案:

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

感謝所有分享想法的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM