- Home /
Change color with delay
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CCSphere : MonoBehaviour {
public Material[] materials;
public Renderer Rend;
private int index = 1;
void Start()
{
Rend = GetComponent<Renderer>();
Rend.enabled = true;
}
void OnMouseDown()
{
if (materials.Length == 0)
return;
if (Input.GetMouseButtonDown(0))
{
index += 1;
if (index == materials.Length + 1)
index = 1;
print(index);
Rend.sharedMaterial = materials[index - 1];
}
}
}
ok so here my script is able to change the color of my object when i click on it but i want to revert the color after one or two secondes
Answer by xxmariofer · Mar 07, 2019 at 12:59 PM
void OnMouseDown()
{
if (materials.Length == 0)
return;
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(ChangeColor());
}
}
IEnumerator ChangeColor()
{
index += 1;
if (index == materials.Length + 1)
index = 1;
print(index);
Material mat = Rend.sharedMaterial;
Rend.sharedMaterial = materials[index - 1];
yield return new WaitForSeconds(2);//2 seconds for exxample
Rend.sharedMaterial = mat;
}
Answer by Saiguru · Mar 07, 2019 at 01:36 PM
Hi @mightofficiel, If you are just looking for a change in the color, there is no need to change the material just we can change the color instead of the material. Just make sure that it's not a default material, then you can try something like this
public class ColorChange : MonoBehaviour
{
//Get Initial Color
Color startColor;
//The new color to be applied
public Color newColor;
public float swtichTime = 3.0f;
void Start()
{
//Get the inital color
startColor = GetComponent<MeshRenderer>().material.color;
}
//Make sure a collider is present on that object
private void OnMouseDown()
{
StartCoroutine(ColorSwitch());
}
IEnumerator ColorSwitch()
{
//Change the color instantly to new color
GetComponent<MeshRenderer>().material.color = newColor;
//Wait for 3 seconds
yield return new WaitForSeconds(swtichTime);
//Switch to the previous color
GetComponent<MeshRenderer>().material.color = startColor;
}
}
Your answer
Follow this Question
Related Questions
Set Color not working on Outline 0 Answers
How Change Color Material By Matrix Value (C#) 0 Answers
Change main color for two or more material 1 Answer
Change sprite on click 0 Answers