Search code examples
c#unity-game-enginereturncoroutine

Can't return a string after value is true in coroutine


I'm having an issue with this coroutine I need to run. It keeps spitting out an error saying that it can't convert WaitUntil to string, and when I add WaitUntil to the return types, it spits another saying it can't be returned. I've tried researching for a few hours now to no avail. Here's the snippit of code:

     public string OpenSaveDialog(string Title, string OpenLocation, string[] AllowedExtentions)
     {
         OpenBtn.GetComponentInChildren<TMPro.TMP_Text>().text = "Save";
         TitleText.text = Title;
         AllowFileNameTyping = true;
         MultiSelect = false;

         LoadIntoExplorer(PathInput, AllowedExtentions);

         return StartCoroutine(WaitForFinish()); // Error here: Cannot implicitly convert type 'UnityEngine.Coroutine' to 'string'
     }

     IEnumerator<string> WaitForFinish()
     {
         yield return new WaitUntil(() => Done == true); // Error here: Cannot implicitly convert type 'UnityEngine.WaitUntil' to 'string'
         yield return FilePathsSelected[0];
     }

Solution

  • You cannot return a value from a Coroutine, your options are making a callback, class scope variable, that indicates the value of the coroutine, custom class, that has an IsDone & value or result property, you also cannot use ref, in or out keywords too because iterators cannot use them :/ so this would not work:

    public IEnumerator WaitForFinnish(ref string value)
    {
        yield return new WaitUntil(() => true);
        value = "value";
    }
    

    So in your case i would do something like this:

    string filePath = string.Empty;
    
    public void OpenSaveDialog(string Title, string OpenLocation, string[] AllowedExtentions)
    {
         OpenBtn.GetComponentInChildren<TMPro.TMP_Text>().text = "Save";
         TitleText.text = Title;
         AllowFileNameTyping = true;
         MultiSelect = false;
    
         LoadIntoExplorer(PathInput, AllowedExtentions);
    
         StartCoroutine(WaitForFinish());
     }
    
     IEnumerator WaitForFinish()
     {
         yield return new WaitUntil(() => Done); // Also don't do bool == true or false,
                                                 // it will trigger most of the programmers :D
         filePath = FilePathsSelected[0];
     }