- Home /
How to get a value from a Coroutine?
This is kinda a pseudo-code to what I want to program:
// attack
// start 0.5f timer
// if within the time, the attack Button is pressed again: attack; else: leave attack mode
To accomplish that, I need to get the value from the timer or the Coroutine, to see if the time is past. So something like:
if (timeValue < 0.5f && keyPressed)
// attack again
else // leave attack mode
Answer by FlaSh-G · Sep 11, 2021 at 01:10 PM
Local variables within a coroutine method are still local variables and cannot be accessed from the outside. You can, however, let the coroutine method use a field declared in the object instead:
private bool coroutineIsRunning = false;
private IEnumerator MyCoroutine()
{
coroutineIsRunning = true;
yield return new WaitForSeconds(0.5f);
coroutineIsRunning = false;
}
Note that I am not using a float variable here, but a bool, since it sounded like you simply wanted to do a thing while the coroutine is running.
Then, simply do
if (coroutineIsRunning && keyPressed)
Now, I am really just guessing here, but it sounds like you also want to prevent the player from performing the action again until the coroutine is started another time. You could set the bool to false when the key is pressed so you cannot press it again, but if you start the coroutine a second time while it is still running, you could run into problems. So what you can do is save a reference to the running coroutine and end it on key press:
private Coroutine runningCoroutine = null;
private IEnumerator MyCoroutine()
{
yield return new WaitForSeconds(0.5f);
runningCoroutine = null;
}
private void StartMyCoroutine()
{
runningCoroutine = StartCoroutine(MyCoroutine());
}
and then do
if (runningCoroutine != null && keyPressed)
{
StopCoroutine(runningCoroutine); // leave attack mode
Attack();
}
Your answer
Follow this Question
Related Questions
Download multiple textures 0 Answers
Make label disappear after 1 second? 3 Answers
Animator.Rebind() not working as expected after manually changing GameObject hierarchy 0 Answers
Returning an IEnumerator as an int? 1 Answer
Coroutine does not work. 1 Answer