- Home /
How to instantly restart a coroutine?
I was wondering to know how to make a coroutine instantly stop and run again (restart).
For example: I'm running a coroutine that smoothly turns alpha from 255 to 0. Before it ends, for example, in the iteration 125, some action happens and this value goes to 255 again and start fading alpha from 255 to 0 from the start. Keep in mind this coroutine will instantly stop just in the time an event occurs, and will start again, in our case from 255 and will fade to 0.
I'm trying to be the clearer I can, if I wasn't, ask me and I'll try to explain again.
Thank in advice and sorry for my bad English.
Answer by Jignesh G. · Nov 23, 2014 at 06:06 PM
First, why you using co-routine of fading affect.? the simplest way is to use iTween.Value to to achieve color fade effect.
public float fromValue = 0;
private IEnumerator valueToExample()
{
iTween.ValueTo( "from", fromValue, "to", 10, "onupdatetarget", gameObject, "onupdate", updateFromValue, "time", 5, "easetype", iTween.EaseType.easeOutExpo );
}
public void updateFromValue( float newValue )
{
fromValue = newValue;
Debug.Log( "My Value that is tweening: " + fromValue );
}
Ulternate Way :
Call IEnumerator like below which can be stopped and start again.
void Start ()
{
StopCoroutine ("fadeTo");
StartCoroutine ("fadeTo");
}
IEnumerator fadeTo()
{
//some code goes here
yield return new WaitForSeconds(1F);
}
Sorry... iTween? I have never heard anything about it! Where is it? What namespace?
it is from the asset store but this i unrelated to your problem here. itween is for interpolating and you are asking about coroutine.
It kind of helped me... StopCoroutine("Fade"); didn't work for me... But I tried StopAllCoroutines(); and it did the work! Is there any problem using StopAllCoroutines ins$$anonymous$$d of StopCoroutine ? Thanks anyway!
The risk of using StopAllCoroutines is you will stop coroutines you want to keep running.
StopCoroutine will only work if you use the string form of StartCoroutine. I believe this is changing in one of the upco$$anonymous$$g releases.
Your answer
Follow this Question
Related Questions
Stop enemy attack coroutine when player is death. 2 Answers
Coroutine doesn't work when called from another method. 3 Answers
Projectiles shoot in time with Update() function, instead of intended firing rate in coroutine. 1 Answer
Loading screen works perfectly with one scene only and not with others 0 Answers
Coroutine Moving 1 Answer