Hi everyone, does anyone here know how to disable coroutines in the next step? for example I have 2 objects (Object A & Object B) and a timer coroutine, The first step: if I put object A in the position of Object B then the coroutine timer runs or starts, Step two: if I put object A in the position of Object B then the coroutine doesn’t start again.
Does anyone here know how to make the script? Thank you…
Without seeing code, could be anything. Coroutines are run by enabled Monobehaviors on active GameObjects.
You can use a bool wich you set on your first step to true and check on the second step.
Coroutines can be stopeed by simply writing:
StopCoroutine(your_Coroutine());
and start again by using
StartCoroutine(your_Coroutine());
But in this way, using bool will be the way to use it, on the first step, make the bool true, on the second step make if statement for bool, and then make the bool false after step 2
No, this is wrong. If you want to stop a running coroutine you have to pass either the Coroutine object that was returned by the StartCoroutine method or you have to pass the exact IEnumerator object that you used to start the coroutine. Your code won’t do anything because calling your_Coroutine()
will just create a new instance of the statemachine and this instance does not represent any running coroutine, so nothing is stopped.
The usual pattern is this:
private Coroutine m_MyRunningCoroutine = null;
void StartMyCoroutine()
{
m_MyRunningCoroutine = StartCoroutine(your_Coroutine());
}
void StopMyCoroutine()
{
if (m_MyRunningCoroutine != null)
{
StopCoroutine(m_MyRunningCoroutine);
m_MyRunningCoroutine = null;
}
}
Though I wouldn’t recommend using StopCoroutine except in some specific cases. The main issue is that stopping a coroutine will terminate the coroutine at the current yield statement. Since this could happen at inconvenient or dangerous moments you should be careful how you design your coroutines. We just had another question about endless running coroutines which are often easier to handle because you have a closed controlled sequence of actions. So you don’t have to worry about the initial condition or any previous steps because the coroutine essentially can only be in one step at a time.
I just wondered when I call StartMyCoroutine() and StopMyCoroutine() ? and is this need a boolean?