How to check if code is running on the unity thread?

Unity isn’t multithreaded. If you start a separate thread and call (eg) Application.isEditor, you get an exception at runtime:

get_isEditor 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.

Let’s assume I have some common code that could run on either the main unity thread or in a separate thread. How do I check if it’s safe for me to call the Unity API?

You could store the main thread into a variable then check the current thread against it to figure out whether it’s the same or not:

using System.Collections;
using System.Collections.Generic;
using System.Threading;

using UnityEngine;

public class MainThreadTest : MonoBehaviour
{
    static Thread mainThread = Thread.CurrentThread;

    // Use this for initialization
    void Start ()
    {
        var thread = new Thread( SomeWork );
        thread.Start();
    }
	
    void SomeWork()
    {
        if(Thread.CurrentThread != mainThread )
        {
            Debug.LogWarning("This is not the main thread.");
        }
    }
}

AI Scripting - Panda BT - Behaviour Tree scripting for Unity.