I want a coroutine to enter by default and then to stop when any input is given to it but then after some code to return again as active. So basically to start and stop a coroutine as many times as it's needed.
-
3\$\begingroup\$ What have you tried? \$\endgroup\$– user35344Commented Aug 18, 2020 at 10:58
-
\$\begingroup\$ Honestly there is no right or wrong answer to this. I would suggest either creating multiple coroutine functions and triggering them when needed, or, if you prefer a single more ugly function, add a conditional loop (ex. while(waitingForInput) { yield return null; }). \$\endgroup\$– Benjamin Danger JohnsonCommented Aug 20, 2020 at 7:48
3 Answers
My approach to this problem would be to create a coroutine which actually runs all the time but changes its behavior based on a bool variable.
public class ToggleableCoroutine : MonoBehaviour
{
private bool coroutineActive;
void Start()
{
StartCoroutine(MyCoroutine());
}
void Update()
{
if (Input.anyKeyDown) {
coroutineActive = !coroutineActive;
}
}
private IEnumerator MyCoroutine() {
while (true) {
if (coroutineActive) {
Debug.Log("Coroutine is active");
}
yield return new WaitForSeconds(1.0f);
}
}
}
-
-
\$\begingroup\$ @user143034 When this answer answered your question, please accept it by clicking the checkmark-icon next to it. \$\endgroup\$– PhilippCommented Aug 18, 2020 at 15:38
Adapted from Philipp's answer. This will start and stop the coroutine as needed.
using System.Collections;
using UnityEngine;
public class ToggleableCoroutine : MonoBehaviour
{
private Coroutine myCoroutine;
void Update()
{
if (Input.anyKeyDown)
{
if (myCoroutine != null)
{
StopCoroutine(myCoroutine);
}
else
{
myCoroutine = StartCoroutine(MyCoroutine());
}
}
}
private IEnumerator MyCoroutine()
{
while (true)
{
Debug.Log("Coroutine is active");
yield return new WaitForSeconds(1.0f);
}
}
}
Although I recommend using Async & Await, instead of Coroutines: Should I use Async & Await, instead of Coroutines, in Unity?
-
\$\begingroup\$ Thank you, i'll check async and await aswell \$\endgroup\$– RODORCommented Aug 18, 2020 at 15:01
If I have not misunderstood, your question just boils down to how you can start and stop a coroutine. Here's how you can do that -
Let this be your coroutine:
IEnumerator DoSomething()
{
//Do that something
yield break;
}
To start the coroutine:
StartCoroutine("DoSomething");
To stop the coroutine:
StopCoroutine("DoSomething");
Now, for your particular requirement, you can do this:
private void Start()
{
StartCoroutine("DoSomething");
}
private void Update()
{
//Stop the coroutine if 'S' key is pressed
if (Input.GetKey(KeyCode.S))
StopCoroutine("DoSomething");
//Start the coroutine if 'W' key is pressed
if (Input.GetKey(KeyCode.W))
StartCoroutine("DoSomething");
}