- Home /
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.
Answer by equalsequals · Jun 03, 2010 at 01:48 PM
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,
==
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 :)
If you want to respond to someone's answer, leave a comment, not another answer.
Your answer
Follow this Question
Related Questions
Load, change material to game object II (not a repeat) 1 Answer
Plane - 10x10 grid - Questions about it. 1 Answer
Spawn object with different material. 0 Answers
How do i get texture from GUI box? 1 Answer
Hair Color 1 Answer