Smokegun
Smokegun

Reputation: 91

Generic coroutines Action parameter

I am trying to make a GET/Post request function that takes in generic parameter and this is my get method:

public static IEnumerator Get<T>(Action<T> callback, string url)
{
    UnityWebRequest www = UnityWebRequest.Get(url);
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        callback(www.error);
    }
    else
    {
        if (typeof(T) == typeof(String))
            callback(www.downloadHandler.text);
    }

}

This is how I use it:

public void GetTest()
{
    string url = "***";

    StartCoroutine(Http.Get<String>((response) => {
        if (response != null)
            Debug.Log(response);
    }, url));
}

But this line:

callback(www.error);

Throws the error that it cannot convert a string to T

That makes sense to me but I don't know how to solve this, this is what I have tried

callback((T)www.error);

callback(www.error as T);

Upvotes: 1

Views: 1405

Answers (2)

Smokegun
Smokegun

Reputation: 91

You have to convert the string to T

This is my solution: callback((T)Convert.ChangeType(www.error, typeof(T)));

Upvotes: 0

Programmer
Programmer

Reputation: 125305

You can't just call the callback directly since it's a generic. Use Convert.ChangeType to convert the www.error or www.downloadHandler.text to Object then cast it to T and finally invoke the callback Action and pass that T to it.

public static IEnumerator Get<T>(Action<T> callback, string url)
{
    UnityWebRequest www = UnityWebRequest.Get(url);
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        T t = (T)Convert.ChangeType(www.error, typeof(T));
        callback(t);
    }
    else
    {
        T t = (T)Convert.ChangeType(www.downloadHandler.text, typeof(T));
        callback(t);
    }
}

While this should work and should solve your compile issues, I see no need to do this. It's totally unnecessary to use generics here. Just using string or byte array to return the result.

Upvotes: 2

Related Questions