CodeBlanks Logo Icon CodeBlanks

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.

Practice Print material assignment state

Assign "MeshRenderer" to renderer and "GoldMaterial" to material. Print Target: MeshRenderer | Assigned: GoldMaterial to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // renderer ve material değerlerini tanımlayıp yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string renderer = "MeshRenderer";
        string material = "GoldMaterial";
        Console.WriteLine("Target: " + renderer + " | Assigned: " + material);
    }
}

Expected output

Target: MeshRenderer | Assigned: GoldMaterial

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer
  • 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

Explanation: Calling renderer.material automatically instantiates a copy of the material to avoid mutating the source asset.

2 Assign material to component

Question
renderer.____ = goldMaterial;
Answer
renderer.material = goldMaterial;

Explanation: In the MeshRenderer component, the 'material' property is used to assign an instanced material at runtime.

3 Material assignment fields

Term Meaning
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

All lessons in Intermediate