is it possible to pause co-routines in Unity until a button is pressed?

edited in Questions and Answers
Hi everyone. Like the title says, is this kind of thing possible?

Comments

  • Here is what I have so far

    using UnityEngine;
    using System.Collections;
    
    public class example : MonoBehaviour {
    	public bool check = false;
    	
    	void Start(){
    		StartCoroutine(Do());
    	}
    	
        IEnumerator Do() {
            SomethingElse();
    		yield return StartCoroutine(Something());
            SomethingElse();
    	}
    		
        IEnumerator Something(){
    		if (Input.GetButton("Jump")){
            	check = true;
    		}
    		while(check == false){
    			yield return new WaitForEndOfFrame();	
    		}
    	}
    	
    	public void SomethingElse(){
    		print("Run");
    	}
    	
    }
  • edited
    So you should be able to do that, and you've pretty much got the right idea.

    I'd do it like this

    public class Example : MonoBehaviour 
    {
    
        bool buttonPressed = false;
    
        public void ButtonWasPressed()
        {
            buttonPressed = true;
        }
    
        public void FunctionThatCallsCoroutine()
        {
            buttonPressed = false;
            StartCoroutine(WaitForButtonPressAndDoSomething());
        }
    
        public IEnumerator WaitForButtonPressAndDoSomething()
        {
            while (!buttonPressed)
                yield return null;
    
            DoSomething();
        }
    
    
        public void DoSomething()
        {
            Debug.Log("OMG BUTTONPRESS!")
        }
    
    
    }


    I haven't tested/compiled this but I'm 99% sure it'll do what you want. "yield return null;" will halt the function until the next frame, upon which it'll try the loop again and halt again if the button hasn't been pressed. When buttonPressed becomes true the loop will exit and your DoSomething function will be called.

    Hope this helps ^_^
    Thanked by 1Duvo
Sign In or Register to comment.