0

Is it true that event in Unity's Monobehavior is single threaded? When I trigger an event, if one of the listener raises an exception, the catch block will be executed. I assume once class A fires an event, the thread will go over each subscriber. When each subscriber finishes, does class A continue in the same thread?

public class EventExample : MonoBehaviour
{
    public delegate void ExampleEventHandler();
    public static event ExampleEventHandler OneDayPassed;

    public void Start NextTurn()
    {
        try {
            if (OneDayPassed != null)
            {
                OneDayPassed();
            }
        }
        catch(Exception e)
        {
            // will catch error here
        }
    }
}

public class EntityWatcher : MonoBehaviour
{
    void Start()
    {
        EventExample.OneDayPassed += this.PrepareNextDay;
    }

    public void PrepareNextDay()
    {
        int test = int.parse("error");
    }
}
GabLeRoux
  • 16,715
  • 16
  • 63
  • 81
weijia_yu
  • 965
  • 4
  • 14
  • 31

2 Answers2

3

Monobehavior is mostly single Threaded but some few callback functions are not. Most of the Unity API callback functions will be made on the main Thread.

These are the fnctions that will not be called on the main Thread which means that you can't call/use the Unity API inside these functions:


As for your own custom event like:

public delegate void ExampleEventHandler();
public static event ExampleEventHandler OneDayPassed;

The event is called on the Thread you invoked it from. If you call it from the main/MonoBehaviour thread, the callback will happen on the main thread. If you create a new Thread and call it from there or use any of the 3 functions listed above then expect it to be called on another Thread other than the main Thread.

If you need to use Unity's API from another Thread other than the main Thread then see this post.

Programmer
  • 121,791
  • 22
  • 236
  • 328
1

Unity's event API is single-threaded. And also, is not designed to support multi-threading (not thread-safe).

Of course, you can explicitly delegate some work with multi-threading if you want, but don't try to call the Unity API with these.

You can have some more information here : https://answers.unity.com/questions/180243/threading-in-unity.html

If you need to rely on some execution order, you can refer to the manual page here

Pac0
  • 21,465
  • 8
  • 65
  • 74