Changing Materials on the Fly


Using Unity Version 2019.4

There are a million reasons you might want to change a material in runtime. This is a really easy tutorial that will show you how. Better yet, it can be easily extended!

Skip to the code.

The (Example) Problem

Your character is wearing an outfit with a material you want to change. You have a new material ready to go, but you don't know how to swap them.

The Solution

The solution for this problem is simple: Create a material-switching code that will take care of the problem!

Step One: Setup

  1. Begin by creating a duplicate material for each material in the mesh renderer that you want to change. I’m using Abigail from my Ultimate Stylized Business Women asset. The prefab I’ve chosen is Outfit 1, which contains several mesh pieces and multiple renderers. For this tutorial, the array index and renderer don't matter. I just want to change the shirt, so I’ll create a duplicate of the blouse material. NOTE: The reason you create a duplicate is because this code only works if the material you are replacing uses the same shader as the material you replaced.

  2. Rename the duplicate to indicate it is your “live material” (I’ve called it “Blouse_Live”).

  3. Replace the old material with this one. In my mesh, there are several materials. Just make sure you put it in the same index as the old one.

  4. Repeat this step for each material you want to be able to change.

Step Two: The Code

Create a new C# script. I called mine “MaterialSwitcher”. Because this method doesn’t actually use the mesh renderer to return the material index, you can put this code on