Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Input.GetKey not working inside Coroutine

Discussion in 'Scripting' started by saifshk17, Apr 23, 2018.

  1. saifshk17

    saifshk17

    Joined:
    Dec 4, 2016
    Posts:
    485
    Hello, Input.GetKey function isn't working inside a coroutine. I am trying to pause a video using GetKey but it isn't taking any kind of input. What is the problem?

    Code (CSharp):
    1.  void Start()
    2.     {
    3.      
    4.             movie = go.GetComponent<VideoPlayer>();
    5.             movie.clip = firstClip;
    6.             movie.Play();
    7.             //yield return new WaitForSeconds(Framepause);
    8.             movie.Pause();
    9.  
    10.        
    11.     }
    12.  
    13. void OnGUI()
    14.     {
    15.         if ((GUI.Button(new Rect(800, 50, 120, 20), "VideoMain")))
    16.         {
    17.              StartCoroutine(MainVid(KeyCode.DownArrow));
    18.         }
    19. }
    20.  
    21. IEnumerator MainVid(KeyCode keyCode)
    22.     {
    23.  
    24.         //ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    25.         // if (Physics.Raycast(ray, out hit) && !movie.isPlaying)
    26.  
    27.  
    28.         if (movie.canSetPlaybackSpeed == true)
    29.         {
    30.             movie.clip = firstClip;
    31.             movie.Prepare();
    32.             movie.playbackSpeed = 1f;
    33.             movie.time = TimeInSecondsToStart;
    34.             movie.Play();
    35.  
    36.         }
    37.  
    38.         if (Input.GetKey(keyCode) && movie.isPlaying)
    39.         {
    40.             //movie.clip = firstClip;
    41.             movie.Pause();
    42.             movie.time = TimeInSecondsToStop;
    43.             movie.Pause();
    44.          
    45.  
    46.         }
    47.  
    48.         yield return null;
    49.     }
    50.  
    51.  
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    Hi saifshk17,

    You are only running the coroutine once. So unless you are holding the key down at that precise moment, the if condition will not be met.

    You will want to add a while loop inside MainVid. Make sure the yield is inside the while loop. Check here for more info on coroutines.
     
    AwesomeGuy5003 likes this.