So what I’m trying to do is to have a menu command that will send a GET request to an API. The problem I’ve run into is that menu item requires the function to be static, while making an http request uses coroutines which requires the function to be non-static (from what I’ve understood and experienced). Here is my (non-working) code :
public class CreateMaterialExample : MonoBehaviour
{
[MenuItem("GameObject/API Request")]
static void APIRequestFromMenu()
{
StartCoroutine("GetRequest", "Parameter");
}
IEnumerator GetRequest(string parameter)
{
UnityWebRequest www = UnityWebRequest.Get("https://www.myurl.com/some/api?parameter="
+ System.Uri.EscapeUriString(parameter));
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
}
}
}
The problem here is that Unity doesn’t want to hear about “StartCoroutine” since it is in a static method. If I remove static Unity complains about the menu item requiring the function to be static.
I would be happy to hear about a solution that doesn’t use coroutines, but in a larger sense I’m curious to know whether it could be possible to use coroutine in menu item functions. I get it if the current implementation makes it impossible, but I can’t see a reason why menu item couldn’t use asynchronous functions.