Search code examples
c#unity-game-engine

How to get all the materials assigned to a GameObject in Unity


In Unity, we can get the material that the GameObject has with the following code.

Material myMaterial = GetComponent<Renderer>().material;

But with the above code, we can only get one material per GameObject.

However, in actually, Unity GameObjects can have more than one material.

As shown in the image below enter image description here

There can be more than one material per GameObject if it is assigned on a face-by-face basis.

I tried to get multiple materials with the code below but it didn't work.

List<Material> myMaterials = GetComponent<Renderer>().material;

Is there a way to get multiple materials assigned to a GameObject?


Solution

  • You can use the Renderer.Materials: https://docs.unity3d.com/ScriptReference/Renderer-materials.html

    List<Material> myMaterials = GetComponent<Renderer>().materials.ToList();