x


Swapping out materials on a skinned mesh renderer?

All,

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?

more ▼

asked Nov 22 '10 at 10:54 PM

csciguy gravatar image

csciguy
59 3 3 4

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Nov 23 '10 at 12:04 AM

skovacs1 gravatar image

skovacs1
10k 11 25 91

I completely keep forgetting that I can expose a public variable in the editor and drag/drop a material/whatever to that variable. I was able to get this working just fine with a single line of code after that.

Thanks!

Nov 23 '10 at 01:34 AM csciguy
(comments are locked)
10|3000 characters needed characters left

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

more ▼

answered Jun 19 '12 at 08:26 PM

sirdavid23 gravatar image

sirdavid23
1 1 1 2

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2193
x1357
x811
x275
x52

asked: Nov 22 '10 at 10:54 PM

Seen: 2465 times

Last Updated: Jun 19 '12 at 08:26 PM