0
GameObject cube = Cube.CreatePrimitive(Cube.CubePivotPoint.UPLEFT);
cube.GetComponent<Renderer>().material.color = Color.blue;

When i assign the color i'm getting exception on the line:

cube.GetComponent<Renderer>().material.color = Color.blue;

MissingComponentException: There is no 'Renderer' attached to the "CubeHolder" game object, but a script is trying to access it. You probably need to add a Renderer to the game object "CubeHolder". Or your script needs to check if the component is attached before using it.

NOTE:

I am using the CUBE class from this answer to create a cube, not the Unity's GameObject.CreatePrimitive function.

Community
  • 1
  • 1
Sharon Giselle
  • 121
  • 2
  • 14

1 Answers1

1

When I wrote the CUBE class, I forgot to mention that the Cubes' renderer is now a child of another Object.

You don't need to add Renderer or MeshRenderer to the cube. It's is already there. The cube is simply a child object and the parent Object is named CubeHolder. You need to use GetComponentInChildren to get its Renderer.

cube.GetComponent<Renderer>().material.color = Color.blue;

should now be:

cube.GetComponentInChildren<Renderer>().material.color = Color.blue;
Community
  • 1
  • 1
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Could you maybe also edit the question itself to include the fact that the OP is using this specific class and not just any gameobject? (as it currently is somewhat of an XY problem and also lacking an MCVE). @Sharon Giselle could/should do that as well. – Keiwan Mar 31 '17 at 21:34
  • That's include because it OP says `Cube.CreatePrimitive(Cube.CubePivotPoint.UPLEFT);` in the question. Although it would be good to link to that old answer. I will do that. – Programmer Mar 31 '17 at 21:36