Delegates and "__ Can only be called from main thread"

Hey folks,

So I’ve run into a bit of a problem.

I’d like to use delegates and event handling in my Unity project to make my workflow much cleaner - however whenever an event is handle and I want it to do something I receive the error "___ Can only be called from the main thread. "

Does anyone have any experience with this? Work around?

Class Network()

public event ActionHandler Action;
public delegate void ActionHandler(string[] action);


private void ProcessAction(string[] message)
{
    Action(message);
}


Class ActionManager()

void Start()
{
        Network.Instance.Action += new Network.ActionHandler(OnActionReceived);
    }

public void Action(string[] action)
{
     if action[0] == 1
     {
       OpenDoor()
      }

}


void OpenDoor()
{
  this.animation.CrossFade("open_glassdoor");
}

Delegates are no problem, it depends on from where you invokre them. Unity uses a single thread for the whole scripting environment, that simplifies everything a lot. That means the whole Unity API is not thread safe. So whenever you access an object from unity or use a method from Unity it has to be invoked from the main thread.

So all depends on where you execute your delegate (the ProcessAction function).

(Btw i guess your “OnActionReceived” should be “Action” or the other way round)

Beside that you shouldn’t name your class Network since Unity already defines a class Network.

This the old STA vs MTA problem. STA does not allow memory allocated on a thread from being manipulated by another thread. It’s ham handed attempt at thread safety, but it is what it is.