How to switch between different materials via c# script?

Hi.

I have a 3d mesh, and I’ve created 2 different materials for it. I have assigned one of them (let’s call it Mat1) to the mesh via the Unity Editor, and I want to be able to change to the other one (let’s call it Mat2) via script.

I’ve created a public Material variable for Mat2, I’ve assigned Mat2 to it via Unity Editor, but when I try to switch to it in-game, I get a “Null ReferenceException: Object reference not set to an instance of an object” error.

I’ve tried doing this with so many different ways, I think it’s no use to list them all here. Please, if anyone knows how to do this, just show me.

:slight_smile:

You’ll want to put the Material into your Resources folder (or create a folder called Resources if you don’t have one) and then you can load it from there and assign it via script like this:

GameObject yourObject;
Material material2;

void Start()
{
    yourObject = GameObject.Find("YourObject");
    material2 = Resources.Load("Material2") as Material;

    yourObject.GetComponent<MeshRenderer>().material = material2;
}