Swapping out materials on a skinned mesh renderer?


I have a single gameobject with a Skinned Mesh Renderer. This renderer has a single material.

I want to swap out this material in game, depending on the situation.

I currently have another material that I would like to swap this out with.

How would I do this via script?

I've tried something like this:

gameObject.renderer.material.mainTexture = (Texture)Resources.Load("black");

But this did not work. Ideas?

You talk of swapping a material, but then your code tries to swap a texture?

Unity does not build into its target builds assets that are not in use. Using Resources.Load will attempt to load the asset at the path specified relative to a Resources folder.

Do you have a Resources folder? Does this folder have a Texture asset called black?

You can use the resources folder if you like, but it will be slower and depends on all of the assets being deployed in that folder and all of your loading must be path specified.

A faster alternative is to store a reference to the material/texture you want to swap like so:

var swapMat : Material;
private var originalMat : Material;

function Start() {
    if(renderer && renderer.material) originalMat = renderer.material;

//Somewhere else
if(swapMat) renderer.material = swapMaterial;

For Texture2D's, it would be about the same.

Could you post the code that worked for you, please? I have the same problem.Thanks.

gameobject.renderer.material.mainTexture = Resources.Load (“black”, typeof(Texture2D))as Texture2D;