// This works
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube)。
Renderer rend = cube.GetComponent<Renderer>()。
rend.material = this.material;
//這不起作用。
GameObject obj1 = Resources.Load($"{basePath}/{this.componentName}") as GameObject;
Renderer rend2 = obj1.GetComponent<Renderer>();
rend2.material = this.material;
Instantiate(obj1, position, Quaternion.identity)。
//這也不能作業。
GameObject obj2 = Resources.Load($"{basePath}/{this.componentName})。) as GameObject;
GameObject instatiatedObj = Instantiate(obj2, position, Quaternion.identity);
Renderer rend3 = instatiatedObj.GetComponent<Renderer>();
rend3.material = this.material;
正如我在評論中所寫的,將材質添加到一個立方體中可以作業,當我試圖將其添加到一個加載的游戲物件中時,卻不能作業,在這兩種情況下,物件都能正確顯示,但沒有材質。
MissingComponentException: 沒有'Renderer'連接到"xxx"游戲物件,但一個腳本正在試圖訪問它。
你可能需要添加一個渲染器到游戲物件 "xxx"。或者你的腳本需要檢查是否組件在使用它之前已經被連接。
預先感謝。
uj5u.com熱心網友回復:
當你實體化一個.obj時,你不是在實體化一個單一的GameObject。當查看層次結構時,你會看到.obj的名稱和一個default物件。
參見:

。
在這種情況下,默認物件將包含物件MeshRenderer組件。
你必須改變你的代碼,使用GetComponentInChildren(Documentation)。
GameObject obj1 = Resources. Load($"{basePath}/{this.componentName}" ) as GameObject;
Renderer rend2 = obj1.GetComponentInChildren<Renderer> ();
rend2.material = this.material;
Instantiate(obj1, position, Quaternion.identity)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/312437.html
標籤:
