Make color pulse every 2 seconds
Hi guys,
I'm pretty new to unity and I'm having a lot of trouble trying to get this code to work how I want it. Here is what I am trying to acheive: An object that starts at 100% alpha then fades out for 1 second While it is not visible, the color is changed It then gets set back to 100% and fades out for 1 second again
My aim is to creating a pulsating color effect.
I found this from another answer which lerps through the colors, but I cant figure out how to get it to my desired result. Any help would be appreciated
void Start() {
colourStart = new Color(Random.value, Random.value, Random.value);
colourEnd = new Color(Random.value, Random.value, Random.value);
//StartCoroutine (changeAlpha ());
}
void Update () {
//transform.localScale = new Vector3 (0, 0, 0);
// Blend towards the current target colour
i += Time.deltaTime*rate;
this.GetComponent<Renderer>().material.color = Color.Lerp (colourStart, colourEnd, i);
// If we've got to the current target colour, choose a new one
if(i >= 1) {
i = 0;
colourStart = this.GetComponent<Renderer> ().material.color;
colourEnd = new Color(Random.value, Random.value, Random.value);
}
}
What does not work? Your script seems fine (except you should store a reference to the Renderer
component in the Awake
or Start
method ins$$anonymous$$d of retrieving it every frame in the Update
)
Sorry I explained badly before. At the moment the code is just smoothly going from one colour to the other, but I'd like it to do a quick pulse where you see a flash of the colour and then it fades out, changes colour and flashes a new colour again.
Answer by Hellium · Mar 26, 2018 at 02:10 PM
If I understood correctly, try this:
private Renderer renderer ;
void Start() {
colourEnd = new Color(Random.value, Random.value, Random.value);
colourStart = colourEnd ;
colourEnd.a = 0 ;
renderer = GetComponent<Renderer>() ;
}
void Update () {
// Blend towards the current target colour
i += Time.deltaTime*rate;
renderer.material.color = Color.Lerp (colourStart, colourEnd, Mathf.PingPong(i * 2, 1) );
// If we've got to the current target colour, choose a new one
if(i >= 1) {
i = 0;
colourEnd = new Color(Random.value, Random.value, Random.value);
colourStart = colourEnd ;
colourEnd.a = 0 ;
}
}
Each colour is changing at the right time now but unfortuneately its changing abruptly and isnt fading out after the colour shows. Is there a way to get it so that once the colour shows, it starts to fade to 0, and once it is invisible the next colour shows up and starts to fade out etc? Thanks for your help!!
I've made some changes to my code, give it a try!
Hey there, its working for me now! Thanks a lot for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220612155406im_/https://answers.unity.com/themes/thub/images/avi.jpg)