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?