- Home /
Simple question about materials
Hello!
I've googled alot and tried many things but I still can't change color of a cube. I use C#, where I create a cube through GameObject.CreatePrimitive(PrimitiveType.Cube). I want it to be a specific color, in this case RGB(30, 225, 86). What's the shortest code for doing that? Also I wonder, if you create a material manually in the editor, how can you apply that material to an object through scripting?
Thanks!
Answer by DaveA · Mar 26, 2012 at 07:12 PM
Did you read this? http://unity3d.com/support/documentation/ScriptReference/Material.Material.html
To set it in the editor, try setting the sharedMaterial rather than the material on the renderer.
Be sure to see this line:
cube.renderer.material = new Material (Shader.Find(" Glossy"));
Yes, so I wrote this:
Shader shader = new Shader();
Color color = new Color(30.0f, 225.0f, 86.0f);
cube.renderer.material = new $$anonymous$$aterial(shader);
cube.renderer.material.color = color;
But when I run it, I get this error:
NullReferenceException UnityEngine.$$anonymous$$aterial..ctor (UnityEngine.Shader shader) (at C:/BuildAgent/work/b0bcff80449a48aa/Runtime/ExportGenerated/Editor/Graphics.cs:1114) Simulation.createFood () (at Assets/Simulation.cs:60) Simulation.addRandomFood () (at Assets/Simulation.cs:66) Simulation.spawnFood () (at Assets/Simulation.cs:36) Simulation.Start () (at Assets/Simulation.cs:22)
If I delete the two last lines, the code works. What could be wrong?