x


How to change a material in Unity

Hello Everybody! I am trying to create a script which would allow me to change a material in realtime. I mean: I have a wall with a wooden material (for example called woody), and I want that when people clicks on it, it will change to another material (for example a "grassy" one). I tried various scripts, but any helped me...

I now I (maybe) have to create an array, but I am not a good programmer atm.

I hope someone can help me and thanks in advance.

more ▼

asked Jun 03 '10 at 01:39 PM

ReNo gravatar image

ReNo
11 1 1 2

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

1 answer: sort voted first

The simple way to implement this is to create a public reference to a Texture2D and assign it the texture you want in the Inspector.

public var myNewTexture2D:Texture2D;

Putting this in your script will allow you to click and drag or select a new texture from the drop down list in your Inspector Panel.

From there when you want to change your texture you just have a reference to the Material you want to swap textures of and assign the new texture using this:

renderer.material.mainTexture = myNewTexture2D; 

This sets whatever the material's "_MainTex" (usually the diffuse texture)

You can also use the Material.SetTexture() method:

renderer.material.SetTexture("_BumpMap", myNewTexture2D);

There really isn't a lot of code other than that. These lines of code are assuming that the script they are implemented in are attached to the game object that has the material you are intending to change.

Cheers,

==

more ▼

answered Jun 03 '10 at 01:48 PM

equalsequals gravatar image

equalsequals
5.1k 16 28 68

Thanks for the help, but can you show me a pseudo-complete script, so I can have an idea on how to use this?

Thx a lot btw :)

Jun 03 '10 at 02:00 PM ReNo

If you want to respond to someone's answer, leave a comment, not another answer.

Jun 03 '10 at 02:05 PM equalsequals
(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:

x5477
x1882
x1176
x522

asked: Jun 03 '10 at 01:39 PM

Seen: 15359 times

Last Updated: Jun 03 '10 at 01:39 PM