Have been having a problem with cycling through materials on a single object using a keyboard button, any suggestions would be appreciated. At the moment the script is cycling through when I press the button, but the material on the object doesn’t change. Clearly I’m missing something very obvious. Thanks for any advice that comes my way.
var arr : Material[];
var no = 0;
if (Input.GetKeyUp("m"))
{
no += 1;
if (no >= arr.length) { no = 0; }
}
(The above script is attached to an object which material I want to change.)
ooops! Don’t I feel stupid. Working really well now, thanks Kaelis!
Just another quick question… How would I go about having the textures fading in over a short period of time, rather than just swapping instantly when I press the button? Is it a lerp, or a fade in/fade out issue?
No not really. Just make sure your using a transparent/xx shader and change the alpha value of the material.color over time in an update function and set the alpha value in the material to completely transparent.
C#
void Update()
{
float fadeSpeed = 100.0f;
Color col = renderer.material.color;
col.a = Mathf.Clamp(col.a + (Time.deltaTime*speed), 0.0f, 1.0f);
renderer.material.color = col; //<-- remember this one..
}
Hope someone (or yourself) can convert this to javascript for you. not that is should be that hard.
PS. might have made this a fadeout script instead. always switch the diretion. if nothing happens try: col.a = Mathf.Clamp(col.a - (Time.deltaTime*speed), 0.0f, 1.0f); instead
Thanks for your help. Below is the script that cycles through the textures. I have managed to get it going forwards and backwards with two buttons. The problem with the fade as I see it is the fact that the previous material still needs to be visible while the next fades in over it. So Material1 has to remain until Material2 is 100% opaque, then Material2 stays until Material3 is 100% opaque (or Material1 if the reverse button is pressed). I am a complete newb at coding so wouldn’t even know where to start with such a complicated system, but at least the code below should give all you experts a good place to start!
Thanks again.
var arr : Material[];
var no = 0;
function Update () {
if (Input.GetKeyUp("m")){
no += 1;
if (no >= arr.length) { no = 0; }
renderer.material = arr[no];
}
if (Input.GetKeyUp("n")){
no -= 1;
if (no <=- arr.length) { no = 0; }
renderer.material = arr[no];
}
}