I am a newcomer to Unity and I am trying to create a scene. I don’t know how to change the color of the objects in my scene. I’ve read some things on materials and meshes, but i don’t get how they relate to the actual color of the object.
So the mesh is the shape of your object and the material is the settings for how that shape will be drawn.
Normally when you want to change the color of something you:
- Create a new material
- Choose a shader
- Set the color/textures required by the shader
A simple shader like Diffuse (the default) will take a color and a texture - more advanced shaders may have many colors and many textures.
Via code you can change a color of a single object by doing:
renderer.material.color = new Color(0.5f,1,1); //C#
renderer.material.color = Color(0.5,1,1); //JS
in new version of unity, API has updated and you must use this codes:
GetComponent.<Renderer>().material.color = Color(0, 255, 0); //Javascript
GetComponent<Renderer>().material.color = new Color(0, 255, 0); //C sharp
There’s a couple ways to do this when you want a shared material.
- PropertyBlock - Gives better
performance but requires customizing
a shader. - Generate materials -
slightly worse performance, but you don’t
have to modify a shader.
PropertyBlock
Using a PropertyBlock involves modifying a shader to have a [PreRendererData] field. Then modifying that field in a script using renderer.SetPropertyBlock(). There’s a great in-depth tutorial to do this at http://thomasmountainborn.com/2016/05/25/materialpropertyblocks/
Generate materials
For solid colors, you can create a script that can be added to gameobjects, such as cubes, that will let you change their color:
[ExecuteInEditMode]
public class ColorSolid : MonoBehaviour
{
public Color ObjectColor;
private Color currentColor;
private Material materialColored;
void Update()
{
if (ObjectColor != currentColor)
{
//helps stop memory leaks
if (materialColored != null)
UnityEditor.AssetDatabase.DeleteAsset(UnityEditor.AssetDatabase.GetAssetPath(materialColored));
//create a new material
materialColored = new Material(Shader.Find("Diffuse"));
materialColored.color = currentColor = ObjectColor;
this.GetComponent<Renderer>().material = materialColored;
}
}
}
Here is a script that changes colors on keypress. You can edit the keys and the colors.
#pragma strict
function Update ()
{
if(Input.GetKeyDown(KeyCode.R))
{
gameObject.renderer.material.color = Color.red;
}
if(Input.GetKeyDown(KeyCode.B))
{
gameObject.renderer.material.color = Color.blue;
}
if (Input.GetKeyDown (KeyCode.T))
{
gameObject.renderer.material.color = Color.white;
}
}
Add this Script to the game object that you want to change color
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Renderer>().material.color = Color.blue;
//Get the renderer component of the object and change the material color to blue
}
}