- Home /
How can I make objects change color, then fade/return to its original color?
I am attempting to make cubes, when collided with another object, be able to have a cube change to green and then fade back into its original color after another object is not touching it anymore. My goal is to make a cube be interacted with (i.e. clicking or touching with another object) and then be able to have the cube fade back into its original color like an LED button would do. I am new to Unity and scripting so I need help with the code. Thanks!
Answer by Saad_Khan · Jun 02, 2015 at 11:30 AM
1) Make two cubes , and check OnTrigger on one of them under the box collider
2) Attach the following script to the cube you want to change the color of ( to red on contact and then fading back to green on exit)
using UnityEngine;
using System.Collections;
public class testScript : MonoBehaviour {
bool toGreen,toRed;
float lerpValue,lerpDuration;
void Start ()
{
toGreen=false;
toRed=false;
lerpValue=0f;
lerpDuration=1f;
}
void Update()
{
if(toRed)
{
//change color to red
gameObject.renderer.material.color = Color.red;
toRed=false;
}
else if(toGreen)
{
// fade color to green
if (lerpValue< 1){
lerpValue += Time.deltaTime/lerpDuration;
gameObject.renderer.material.color = Color.Lerp(Color.red, Color.green, lerpValue);
}
else
{
toGreen=false;
lerpValue=0f;
}
}
}
void OnTriggerStay()
{
toRed=true;
}
void OnTriggerExit()
{
toGreen=true;
}
}
You can change the Lerp Duration variable to change how long it takes to fade.
Theres is also an option of doing this with OnCollision instead of OnTrigger
This is great, but can you add functionality that pulls the original color that it resets to rather than a color defined in the script?