Game Development
Assigning a material
Learn to assign a material to a MeshRenderer.
Assigning Material to MeshRenderer
To modify an active material at runtime, interact with the MeshRenderer component. Assigning to renderer.material causes Unity to instantiate an independent material clone exclusive to this object.
MeshRenderer renderer = GetComponent<MeshRenderer>();
// Binding a new material to the object
renderer.material = newMaterial;
This safeguards other objects sharing the same base asset from accidental color mutations.
Multiple Materials and sharedMaterial
When a 3D mesh contains multiple sub-meshes, the renderer.materials array allows mapping a unique material to each sub-mesh slot.
// Accessing the material of the first sub-mesh
Material firstPart = renderer.materials[0];
// Assigning by sharing the original project asset
renderer.sharedMaterial = baseMaterial;
Sharing the exact disk asset without instantiating copies saves memory and is done using sharedMaterial.
Exercise Print material assignment state
Assign "MeshRenderer" to renderer and "GoldMaterial" to material. Print Target: MeshRenderer | Assigned: GoldMaterial to the console.
Show example solution
using System;
class Program
{
static void Main()
{
string renderer = "MeshRenderer";
string material = "GoldMaterial";
Console.WriteLine("Target: " + renderer + " | Assigned: " + material);
}
}
Test yourself
-
What happens when modifying an object's material via 'renderer.material' in code?
- An independent material clone (instance) is created and assigned to that object
- All objects sharing that material in the project are deleted from the scene
- The polygon count of the model is automatically doubled
- All lights in the scene are completely disabled
Show answer
An independent material clone (instance) is created and assigned to that object — Calling renderer.material automatically instantiates a copy of the material to avoid mutating the source asset.
-
Assign material to component
renderer.____ = goldMaterial;
Show answer
renderer.material = goldMaterial;
-
Material assignment fields
- MeshRenderer
- Component rendering mesh with material
- material
- Access to instanced material copy
- materials
- Material array for multiple sub-meshes
- sharedMaterial
- Access to original shared material
Next lesson: Summary - Material