如何從具有多個子對象的.GetComponentInChildren
中選擇從哪個子組件獲取組件?如何選擇使用GetComponentInChildren獲取哪個子組件時,如果有多個子對象
通過此代碼,我得到僅第一個孩子的MeshRenderer
。
selectedObj.GetComponentInChildren<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);
如何從具有多個子對象的.GetComponentInChildren
中選擇從哪個子組件獲取組件?如何選擇使用GetComponentInChildren獲取哪個子組件時,如果有多個子對象
通過此代碼,我得到僅第一個孩子的MeshRenderer
。
selectedObj.GetComponentInChildren<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);
如果你知道了你是後組件的子對象的唯一名稱,你可以使用transform.FindChild("nameOfChildObject")
找到你正在尋找的特定子對象。所以你的情況,你可以說:
selectedObject.transform.FindChild("nameOfChildObject").GetComponent<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);
非常感謝我用一行代碼完成的工作。 – N1ckGreek
GetComponentInChildren
無法做到這一點。您可以在GetChild
函數的幫助下,通過子對象GameObject的索引來完成此操作。下面的代碼會得到一個子遊戲物體的成分與3
int CHILD_INDEX = 3;
selectedObj.transform.GetChild(CHILD_INDEX).GetComponent<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);
索引製作自定義的通用擴展方法,這和指標參數添加到GetComponentInChildren
功能:
public static class ExtensionFunction
{
public static T GetComponentInChildren<T>(this GameObject gameObject, int index)
{
return gameObject.transform.GetChild(index).GetComponent<T>();
}
}
然後你就可以這樣做:
int CHILD_INDEX = 3;
selectedObj.GetComponentInChildren<MeshRenderer>(CHILD_INDEX).material.SetColor("_EmissionColor", Color.red);
使用FindChild
你只是想從一個孩子游戲物體只會遊戲特別慢下來讓組件的每個時間如果你做了很多。
感謝您的幫助,但James Hogle的答案完全符合我想要的一行代碼。雖然你的代碼對於更復雜的算法可能會更好。 – N1ckGreek
您可以參考您想要編輯材料的特定小孩嗎?除此之外,如果您想要更改多個孩子,您可以在需要編輯的腳本中添加一個腳本並獲取該組件,然後從該腳本編輯該材料。 – Alox
你知道你想從運行時獲得組件的子對象的名字嗎?這是一個獨特的名字嗎? –
我在運行時知道孩子的名字。我正試圖找到最好的方式來做到這一點。我有一個TileManager腳本處理幾乎所有並在其中有一些變量瓷磚一個腳本這\t'無效onmousedown事件(){ \t \t \t \t //讓瓷磚經理知道有在印刷機上(這)瓷磚 \t \t tilesManager.OnObjectSelection(this.gameObject); \t}' – N1ckGreek