- Home /
Trying to make a renderer blink on and off, it's not working but I get no errors when building?
Here is my code:
IEnumerator blinkTime () {
if (blinking == true) {
blinkTimeOn = true;
while (blinkTimeOn == true) {
renderer.enabled = false;
yield return new WaitForSeconds (1f);
blinkTimeOff = true;
blinkTimeOn = false;
}
while (blinkTimeOff == true) {
renderer.enabled = true;
yield return new WaitForSeconds (1f);
blinkTimeOn = true;
blinkTimeOff = false;
}
}
}
I'm trying to make an object's renderer be enabled for a second then disabled for a second and this will repeat until blinking is set to false.
What exactly am I doing wrong here?
Edit: I should point out that I have "blinkTime" being called here:
void OnTriggerEnter(Collider otherObject) {
if (otherObject.gameObject.CompareTag ("Enemy")) {
playerLives--;
Timer = Time.time;
blinking = true;
blinkTime();
if (playerLives < 1) {
Destroy(this.gameObject);
}
}
For one thing your logic is way overcomplicated for what you are trying to do. The three blink booleans can all be nuked unless you use their values outside the Coroutine (the code you provided doesn't).
IEnumerator blinkTime () {
renderer.enabled = false;
yield return new WaitForSeconds (1f);
renderer.enabled = true;
}
This is basically equivalent to your Coroutine code.
Agree with Huacanacha, but wanted to add that there is no reason to have two booleans that always store the opposite values of each other (like blinkTimeOn and blinkTimeOff).
Lets say blinkTimeOn was true, but you wanted something to happen when blinkTimeOn wasn't true. You just use an exclamation point (!) to invert the polarity of the value.
if (blinkTimeOn)
{
// blinkTimeOn is true
}
if (!blinkTimeOn)
{
// blinkTimeOn is false
}
Answer by iwaldrop · Nov 25, 2013 at 01:37 AM
The reason it isn't working is because you're not calling blinkTime via the StartCoroutine method.
enter code herevoid OnTriggerEnter(Collider otherObject) {
if (otherObject.gameObject.CompareTag ("Enemy")) {
playerLives--;
Timer = Time.time;
blinking = true;
blinkTime();
if (playerLives < 1) {
Destroy(this.gameObject);
}
}
Should be:
void OnTriggerEnter(Collider otherObject) {
if (otherObject.gameObject.CompareTag ("Enemy")) {
playerLives--;
Timer = Time.time;
blinking = true;
StartCoroutine(blinkTime());
if (playerLives < 1) {
Destroy(this.gameObject);
}
}
Thank you iwaldrop and thank you Huacanacha! I will give these a try and hopefully will get the result I want. Thank you again for the help :)
Edit: Great success. Combining both your answers has given me exactly what I was wanting in the first place!
Your answer
![](https://koobas.hobune.stream/wayback/20220613122654im_/https://answers.unity.com/themes/thub/images/avi.jpg)