- Home /
How to make a sprite toggle on and off after a few seconds?
Basically what I am trying to do is to gave a sprite that is on my screen to blink on for a few seconds and then blink off, and I want this to happen as a constant loop. I know instead of deactivating the game object itself I should just activate and deactivate the renderer and use wait for seconds for the pauses, but I am unsure how this script is would be formatted. If anybody can help me that would be great. Thank you in advance.
edit I also just wanted to make note that the sprite I am using is through Unity 5`s UI system.
Answer by jcv8000 · Apr 03, 2015 at 01:08 PM
public GameObject theSprite;
void Start()
{
StartCoroutine(StartBlinking()); //Doesn't need to be in Start() but use this line wherever you need it.
}
IEnumerator StartBlinking()
{
yield return new WaitForSeconds(1); //However many seconds you want
theSprite.GetComponent<SpriteRenderer>().enabled = !theSprite.GetComponent<SpriteRenderer>().enabled; //This toggles it
StartCoroutine(StartBlinking());
}
In the editor drag the sprite into the "The Sprite" box. Or you could attach this script to the sprite itself and replace "theSprite" in the code with "this".
If you want to stop the blinking, use this:
StopAllCoroutines();
theSprite.GetComponent<SpriteRenderer>().enabled = true;
Since this is stopping all coroutines in the whole script, you should probably keep this in a script by itself or make sure you have no other coroutines in the script.
So I tried your script and it didn`t pull any errors, but it will only blink one time. It will only activate if it is currently deactivated or vice versa, it didn`t create the looping effect I was hoping for. What I am trying to achieve is that it flashes onscreen on and off in a constant loop. And again thank you for replying!
Oh sorry I did that wrong. Change the IEnumerator StartBlinking to this:
IEnumerator StartBlinking()
{
yield return new WaitForSeconds(1); //However many seconds you want
theSprite.GetComponent().enabled = !theSprite.GetComponent().enabled; //This toggles it
StartCoroutine(StartBlinking());
}
I've tested this and it works :) I'll update the original answer with this.
One final edit and I have the way to stop blinking working :) Sorry about all that :P
Answer by Notter · Apr 03, 2015 at 01:07 PM
You can use a Coroutine it's basically a method that runs independent of the frame-rate.
Unity describes how to use it in it's documentation: http://docs.unity3d.com/ScriptReference/Coroutine.html
so, at your Start() function, use: StartCoroutine("name"); and your coroutine should disable/enable the sprite renderer and then WaitForSeconds