預製層次:在Unity中,如何使用腳本訪問預製件的兒童組件?
按鈕
1文本
2圖像
我希望訪問預製的圖像子組件。
我嘗試以下的代碼:
GameObject addTypeButton = (GameObject)Instantiate(prefabButton);
addTypeButton.transform.SetParent(ParentPanel, false);
//set text
addTypeButton.GetComponentInChildren<Text>().text ="Some string";
//get image
WWW www = new WWW("someImagelink");
yield return www;
//set image
addTypeButton.GetComponentInChildren<Image>().sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width,www.texture.height), new Vector2(0, 0));
然而,上述代碼被訪問按鈕(內置)的圖像的腳本。 不是圖像UI組件。 如何訪問UI圖像(子)組件?
請幫忙。
謝謝!
3個答案,但只有這一個才能真正完成這項工作。 'GetChild'比'Find'好。 – Programmer
我想補充一點,依賴對象名稱或層次結構順序可能並不總是最安全的解決方案。對於更強大的一個,你可以使用'GetComponentsInChildren()'並檢查返回_Image_s是否與你按鈕上的不同(不過這會比較慢)。 –
Kardux