0

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() {

        ...
    }
}
Paul Nylund
  • 341
  • 1
  • 4
  • 7
  • Does removing the `Task.Run` stop the exception occurring? – mjwills Nov 06 '18 at 01:09
  • Yes it does! But I need the PostRequest() method to complete before moving onto the next task (in reality, there are two others in Main.cs). Maybe there's a better way? – Paul Nylund Nov 06 '18 at 01:14
  • `StartCoroutine` is being called from another but you can't call Unity API from another thread. See the duplicate then try something like this: `UnityThread.executeInUpdate(() => { instance.StartCoroutine(PostRequest()); });` – Programmer Nov 06 '18 at 01:42

0 Answers0