- Home /
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?
Answer by ericbegue · Jan 18, 2017 at 03:12 PM
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.
Do not initialize your static variable like that:
static Thread mainThread = Thread.CurrentThread;
Unity loades your scene in a background thread. So you can't ensure that the thread which accesses your class the first time is the main thread. You should gather the value in Awake or any other callback that is ensured to actually run on the main thread.
I was not aware about that. So Unity is multi-threaded internally?
Yeah, unity IS multithreaded, but *the unityengine api is NOT threadsafe. And some things occur on different threads (scene loading, rendering etc), and this varies per platform.
Your answer
Follow this Question
Related Questions
MonoBehaviour.Invoke and Threading 2 Answers
Multithreading freezes editor 1 Answer
Getting current time from the worker thread 1 Answer
How to use MultiThreading to remove momentary unresponsiveness 0 Answers
Threaded procedural animation 0 Answers