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. Dismiss Notice

Question Passing IEnumerator as a parameter with parameters

Discussion in 'Scripting' started by Flamacore, Jul 5, 2021.

  1. Flamacore

    Flamacore

    Joined:
    Dec 17, 2013
    Posts:
    137
    Probably a very basic knowledge is required to do this but it seems all my years of programming did not teach me this particular case. Here's a code snippet with the part that I've added to demonstrate what I need which obviously gives an error if I use it:
    Code (CSharp):
    1. public IEnumerator GetItemTable(string url, IEnumerator onFinishedCallback)
    2.         {
    3.             UnityWebRequest unityWebRequest = UnityWebRequest.Post(url, "");
    4.             yield return unityWebRequest.SendWebRequest();
    5.             if (String.IsNullOrEmpty(unityWebRequest.error))
    6.             {
    7.                 if (onFinishedCallback!= null)
    8.                     StartCoroutine(onFinishedCallback(unityWebRequest.downloadHandler.text));
    9. //THIS IS WHAT I'M TRYING TO DO BUT OBVIOUSLY GIVES ERROR
    10.             }
    11.             else
    12.             {
    13.                 Debug.Log("Error getting items list")
    14.                 //other stuff
    15.             }
    16.         }
    So is there a way for me to add parameters to onFinishedCallback?
     
  2. VolodymyrBS

    VolodymyrBS

    Joined:
    May 15, 2019
    Posts:
    150
    To make your code works you need to change IEnumerator to Func<string, IEnumerator>

    But in my opinion, it's cleaner to change IEnumerator to Action<string> and do not start coroutine in GetItemTable. Let caller decide what to do in the callback. If caller needs a coroutine that's caller responsibility to start it.
     
    Flamacore likes this.
  3. Flamacore

    Flamacore

    Joined:
    Dec 17, 2013
    Posts:
    137
    Good point actually. Thanks a lot for the tip. Seems I've never used Func<> syntax before :)