I'm pretty new to Unity, I'm sure it's a stupid question, I'm trying to add a Material to a GameObject, here's my code:
// this works
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Renderer rend = cube.GetComponent<Renderer>();
rend.material = this.material;
// this does not work
GameObject obj1 = Resources.Load($"{basePath}/{this.componentName}") as GameObject;
Renderer rend2 = obj1.GetComponent<Renderer>();
rend2.material = this.material;
Instantiate(obj1, position, Quaternion.identity);
// this does not work too
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;
As I wrote in comment adding the material to a cube works, when I'm trying to add it to a loaded game object does not work, in both cases objects are displayed correctly but without material. In Unity the following error is displayed:
MissingComponentException: There is no 'Renderer' attached to the "xxx" game object, but a script is trying to access it.
You probably need to add a Renderer to the game object "xxx". Or your script needs to check if the component is attached before using it.
Thanks in advance.
CodePudding user response:
When you are instantiating an .obj
you are not instantiating a single GameObject. When looking at the hierachy you will see the name of the .obj
and a default
object.
See:
In that case the default object will contain the objects MeshRenderer
component.
You have to change your code to use 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);