- Home /
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.
:)
Answer by cjdev · Aug 28, 2015 at 09:41 PM
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;
}
Thanks for that. It works just fine.
Just one more question: what if the material I need is already assigned to some other gameObject? Isn't it already loaded that way? Could I just re-use it, like this?
$$anonymous$$aterial mat2; mat2 = someOtherObject.GetComponent().material; myObject.GetComponent().material = mat2;
Yeah you could, but don't forget the type in GetComponent(). You'd basically just be storing a reference to the material in your variable and then assigning it (a reference to the $$anonymous$$aterial, not the actual $$anonymous$$aterial) to another GameObject as well.
Why does the folder have to be called Resources? Is that absolutely necessary, or is it just like... the usual thing to do? I ask because I'm essentially trying to do the same thing, only, I want to use a button to toggle which material is assigned to the render of a specific object. Unity never created a specific "Resources" folder for me, so, what I'm wondering is, do I just use whatever folder I myself created? Or is there something specific in the API or whatever that requires you call it that way?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Changing material on an object multiple times 0 Answers
Gl.Lines appearing over objects 0 Answers
Cannot implicitly convert type UnityEngine.MeshRenderer to UnityEngine.Material. 1 Answer