Coroutines

Hello there,
I spent quite some time figuring out how to make a coroutine, but now that I understood the syntax (or so I thought), I ran into another problem, which is probably due to a misunderstanding of the coroutine basics

aiming = true;
            wait = GameObject.FindWithTag ("Player").GetComponent<WaitForInput>();
            Debug.Log ("Press space to sort of fire");
            wait.Aim (KeyCode.Space);
            Debug.Log ("Coroutine over");
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            Debug.DrawRay (Input.mousePosition, Vector3.forward);
            Debug.Log ("Raycast just hit");

In the 3rd line I wrote wait.Aim, which calls a Coroutine from another script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaitForInput : MonoBehaviour {

    IEnumerator WaitInput(KeyCode keyCode){
        while (!Input.GetKeyDown(keyCode)) {
            Debug.Log ("Returning null");
            yield return null;
        }
    }

    public void Aim(KeyCode keyCode){
        StartCoroutine (WaitInput(keyCode));
        }
    }

I assumed that doing this would “freeze” my 1st code until the 2nd code, with the coroutine, had its condition met

But what I get is : I get a ton of “Returning null” in my debug, showing the coroutine is active, and it stops when I press Space (as stated in wait.Aim(KeyCode.Space))
The problem is, even though the coroutine is stopping only when I press space, the first code still progresses and show me “Raycast just hit” debug log. dont pay attention to what it actually does, the point is that what is written in code AFTER the coroutine still executes before the coroutine is done :frowning:

The purpose of this coroutine was supposed to make me able to wait for an input before executing the rest of the code

How do I do that ?

Thanks in advance

The “aim” function just started the coroutine. It wasn’t a coroutine, so it finished and then went back and finished the rest of the code.

I think you would have to use WaitInput directly, or make Aim a coroutine.


wait = GameObject.FindWithTag (“Player”).GetComponent();
Debug.Log (“Press space to sort of fire”);
yield return wait.WaitInput(KeyCode.Space);
Debug.Log (“Coroutine over”);

@Stardog
Well I tried this but for a reason that I don’t quite get, i get no automatic completion beyond wait. in yield return wait.WaitInput(KeyCode.Space);
And if I make Aim a coroutine, I can’t access it, like WaitInput :frowning:
Which is why I made this Aim in the first place, to be able to access the coroutine

Thanks for your answers