I'm trying to reference one script from another in Unity. One of these scripts (API.cs) is sending a Post request to a server, while the other (Main.cs) is attempting to run its Post() method.
However, I am seeing the following error message in the Unity debugger:
IsObjectMonoBehaviour can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
API:Post(MonoBehaviour) (at Assets/Scripts/API.cs:7)
Main:m__0() (at Assets/Scripts/Main.cs:13)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()
I think this error has something to do with calling the non-static method, PostRequest() from within the StartCoroutine() method. However, I cannot make an IEnumerator "public static".
This is the first project I've ever worked on in both C# and Unity, and I'm kind of at a loss here...
Would really appreciate your input!
Main.cs
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
public class Main : MonoBehaviour {
void Start() {
Task one = Task.Run(() => {
API api = new API();
api.Post(this);
});
one.Wait(-1);
}
}
API.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class API {
public void Post(MonoBehaviour instance) {
instance.StartCoroutine(PostRequest());
}
IEnumerator PostRequest() {
...
}
}