Quick answer: Unity’s API may only be used on the main thread. The error has two sources. A Unity call in a MonoBehaviour or ScriptableObject constructor or field initializer: move it to Awake or Start. Or a Unity call on a background thread (Task.Run, a socket callback, a timer): do the Unity part on the main thread through a queue drained in Update, SynchronizationContext.Post, or await Awaitable.MainThreadAsync() in Unity 6.

Two of the three lines in this message talk about constructors and field initializers. If your code sits in a socket callback or inside Task.Run, that advice has nothing to do with your problem, and Unity prints it anyway. The same text covers two unrelated mistakes, so the first job is working out which one you made. This guide shows the exact messages and what the first word of each means, a quick way to tell the two situations apart from the stack trace, and the fixes for both, with code for Unity 2022 LTS and Unity 6.

The exact messages

UnityException: get_transform 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.

The first word is the engine’s internal name for the member you used. A property read shows up as get_ plus the property name, a write as set_.

Message starts withWhat your code called
get_transform, get_gameObjecttransform, gameObject on any component
GetComponentFastPathGetComponent<T>()
FindGameObject.Find("...")
Internal_CreateGameObjectnew GameObject()
SetActivegameObject.SetActive(...)
get_isPlaying, get_isDebugBuildApplication.isPlaying, Debug.isDebugBuild
get_persistentDataPathApplication.persistentDataPath
HasKeyPlayerPrefs.HasKey("...")

There is a second wording for the constructor case. When the constructor runs on the main thread, which is common in the editor, Unity prints this instead:

UnityException: Find is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'Spawner' on game object 'Spawner'.
See "Script Serialization" page in the Unity Manual for further details.

For a ScriptableObject the same message tells you to use OnEnable. All of these are one rule: nearly everything in UnityEngine that touches objects, scenes, assets, time or player settings must be called from the main thread, during the normal script callbacks.

Which of the two situations you are in

Read the stack trace under the message.

When in doubt, log the thread. Debug.Log is safe to call from any thread:

Debug.Log($"thread {System.Threading.Thread.CurrentThread.ManagedThreadId}");

Print it once from Awake to learn the main thread’s ID, then from the suspect code.

Situation A: constructors and field initializers

You do not construct MonoBehaviours and ScriptableObjects; Unity does, while it loads and deserializes a scene or asset, and that work can run on a loading thread. Whatever sits in the constructor or to the right of a field’s = runs at that moment.

// Broken
public class Spawner : MonoBehaviour
{
    GameObject player = GameObject.Find("Player");
    string savePath = Application.persistentDataPath + "/save.json";
}
// Fixed
public class Spawner : MonoBehaviour
{
    GameObject player;
    string savePath;

    void Awake()
    {
        player = GameObject.Find("Player");
        savePath = Application.persistentDataPath + "/save.json";
    }
}

Field initializers are fine for plain C# values: numbers, strings, new List<int>(), your own non-Unity classes. Unity’s manual lists Debug.Log and maths on simple types such as Vector3 as safe as well.

The same rule reaches two places people overlook. A plain class marked [Serializable] and used as a field on a MonoBehaviour has its constructor run during deserialization too. And a static initializer such as static readonly string SavePath = Application.persistentDataPath; runs the first time anything touches the class, on whatever thread that happens to be. Assign statics from Awake, or from a method marked [RuntimeInitializeOnLoadMethod].

Situation B: where background threads come from

If you never wrote new Thread, the thread came from a library. These all run your code off the main thread:

  1. Task.Run, ThreadPool.QueueUserWorkItem, new Thread. The body of the lambda runs on another thread, including any Unity call inside it.
  2. Task continuations that left the main thread. An await started on the main thread resumes on the main thread, because Unity installs its own synchronization context. ConfigureAwait(false) opts out of that, ContinueWith runs on the thread pool by default, and an await inside code that is already on a pool thread stays on the pool. Firebase callbacks are the usual example: use ContinueWithOnMainThread from Firebase.Extensions in place of ContinueWith.
  3. Network callbacks. Socket, TcpClient and UdpClient async callbacks, the message events of most WebSocket libraries, SerialPort.DataReceived.
  4. Timers and watchers. System.Timers.Timer.Elapsed, System.Threading.Timer callbacks, FileSystemWatcher events.
  5. Native and platform callbacks. Callbacks from a native plug-in, Java callbacks on Android, and OnAudioFilterRead, which Unity documents as running on the audio thread.
  6. Finalizers. A ~MyClass() method runs on the finalizer thread.

The fix is always the same shape: keep the slow or blocking work on the background thread and move only the Unity calls to the main thread. Four ways to do that follow, from least machinery to most.

Fix 1: read what you need before the thread starts, apply results after

// Broken: both Unity calls run on a pool thread
async void Start()
{
    await Task.Run(() =>
    {
        string path = Application.persistentDataPath + "/level.json";
        LevelData data = LevelParser.Parse(File.ReadAllText(path));
        titleLabel.text = data.title;
    });
}
// Fixed
async void Start()
{
    string path = Application.persistentDataPath + "/level.json";   // main thread

    LevelData data = await Task.Run(
        () => LevelParser.Parse(File.ReadAllText(path)));          // background

    titleLabel.text = data.title;                                   // main thread again
}

Strings, numbers, Vector3 values and your own data classes can cross threads freely. Anything derived from UnityEngine.Object cannot be used on the other side. Do not add ConfigureAwait(false) to the await, or the last line runs on the pool thread.

Fix 2: a main-thread dispatcher

For callbacks you do not control (sockets, timers, plug-ins), queue an action and run it from Update:

using System;
using System.Collections.Concurrent;
using UnityEngine;

public class MainThreadDispatcher : MonoBehaviour
{
    static readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void Create()
    {
        var go = new GameObject("MainThreadDispatcher");
        go.AddComponent<MainThreadDispatcher>();
        DontDestroyOnLoad(go);
    }

    public static void Enqueue(Action action) => queue.Enqueue(action);

    void Update()
    {
        while (queue.TryDequeue(out Action action))
        {
            try { action(); }
            catch (Exception e) { Debug.LogException(e); }
        }
    }
}
// On the socket thread
void OnMessage(string text)
{
    MainThreadDispatcher.Enqueue(() => chatLabel.text = text);
}

The action runs at most one frame later. If a thread can produce thousands of messages a frame, queue the data and process a capped number per frame, so a burst cannot stall the game.

Fix 3: SynchronizationContext.Post

Unity already has a dispatcher: the UnitySynchronizationContext it installs on the main thread. Capture it once and post to it from anywhere:

SynchronizationContext mainContext;

void Awake()
{
    mainContext = SynchronizationContext.Current;   // captured on the main thread
}

void OnTimerElapsed(object sender, ElapsedEventArgs e)   // pool thread
{
    mainContext.Post(_ => statusLabel.text = "Saved", null);
}

Post queues the callback and returns immediately; Unity runs it on the main thread during the player loop. Avoid Send, which blocks the calling thread until the main thread has run the callback. If the main thread is itself waiting for that thread, with Join or Task.Wait, both wait forever.

Fix 4: Awaitable in Unity 6, or UniTask

Unity 2023.1 added the Awaitable class, so it is available in Unity 6 and not in 2022 LTS. Two static methods switch threads inside one method:

async Awaitable LoadLevelAsync(string path)
{
    await Awaitable.BackgroundThreadAsync();
    LevelData data = LevelParser.Parse(File.ReadAllText(path));   // thread pool

    await Awaitable.MainThreadAsync();
    BuildLevel(data);                                             // Unity API allowed
}

MainThreadAsync completes immediately when you are already on the main thread, so it is cheap to call defensively at the top of any method that touches Unity objects. On 2022 LTS, the third-party UniTask package offers the same pattern with await UniTask.SwitchToThreadPool() and await UniTask.SwitchToMainThread().

What happens in builds

The exception is a check, and the check is not present everywhere. Unity’s manual says of the loading-thread case that development builds throw an error, while in a release build “the code runs without errors but can produce crashes and other unexpected behavior”. Treat calls from your own threads the same way: outside the editor and development builds, do not count on an exception. The call may appear to work, return stale data, or crash natively some time later. That rules out try/catch as a fix, and it is the reason to remove every occurrence you see in the editor even when the game seems fine.

WebGL is a separate case. Unity’s WebGL player does not support C# threads at all, so Task.Run and System.Threading.Timer code needs a different design there, not a dispatcher.

How to confirm the fix

Run the path in the editor and in a development build, since both perform the check. For network and timer code, let it run long enough for the callback to fire several times, and trigger the error paths as well: disconnects and timeouts often have their own callback that updates UI. Search the project for Task.Run, ContinueWith, ConfigureAwait(false) and new Thread, and read each body for anything from UnityEngine. Then confirm the background work is still off the main thread: a fix that moves the whole job to the main thread trades this error for a frozen frame.

What an error reporter can and cannot see here

Threading errors are easy to lose. The Bugnet Unity SDK files exceptions by listening to Application.logMessageReceived, and Unity raises that event on the main thread only. An exception logged from a worker thread does not reach it, and an exception trapped inside a task nobody awaits is never logged at all. So make the failure visible on the main thread: catch on the worker and pass the exception to the dispatcher above, where Debug.LogException(e) turns it into a report with the stack trace, recent log lines, platform and game version. In release builds, where the bad call may not throw, Bugnet has nothing to capture from the call itself; what you get is the player’s own report from the in-game form with device details attached, and any later exception the corrupted state causes. The getting started guide covers setup.

Frequently asked questions

What does can only be called from the main thread mean in Unity?

Almost all of the Unity API must be used on the main thread, the one that runs Awake, Start and Update. The error means a Unity call ran somewhere else: inside a constructor or field initializer executed while a scene was loading, or on a background thread such as a task, timer or socket callback.

Why does the message mention constructors and field initializers when my code runs in a thread?

Unity prints the same three lines for every off-main-thread call, and the wording assumes the most common beginner cause. If your stack trace shows System.Threading, a timer or a socket and no constructor frame, ignore that advice and move the Unity call back to the main thread.

How do I run code on the main thread from another thread in Unity?

Queue it. Put an Action in a ConcurrentQueue and run the queue from Update, or capture SynchronizationContext.Current on the main thread and call Post on it from the other thread. In Unity 6 you can also await Awaitable.MainThreadAsync inside an async method.

Does async and await run my code on a background thread in Unity?

Not by itself. An await that starts on the main thread resumes on the main thread, because Unity installs its own synchronization context. Code only leaves the main thread when you use Task.Run, ConfigureAwait false, ContinueWith, or a library that calls you back from its own thread.

Why does the call seem to work in a release build but throw in the editor?

The thread check runs in the editor and in development builds. Unity’s manual says that in a release build the code runs without errors but can cause crashes and other unexpected behavior. The absence of an exception does not make the call safe.

Ignore the constructor advice until you have read the stack trace. A .ctor frame means move the code to Awake; anything from System.Threading means queue the Unity call back to the main thread.