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.

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,

==