forked from IvanMurzak/Unity-MCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainThreadDispatcher.cs
More file actions
77 lines (65 loc) · 2.8 KB
/
MainThreadDispatcher.cs
File metadata and controls
77 lines (65 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
┌──────────────────────────────────────────────────────────────────┐
│ Author: Ivan Murzak (https://github.com/IvanMurzak) │
│ Repository: GitHub (https://github.com/IvanMurzak/Unity-MCP) │
│ Copyright (c) 2025 Ivan Murzak │
│ Licensed under the Apache License, Version 2.0. │
│ See the LICENSE file in the project root for more information. │
└──────────────────────────────────────────────────────────────────┘
*/
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Threading;
using UnityEditor;
using UnityEngine;
namespace com.IvanMurzak.Unity.MCP.Runtime.Utils
{
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class MainThreadDispatcher : MonoBehaviour
{
public static int MainThreadId = Thread.CurrentThread.ManagedThreadId;
public static bool IsMainThread => Thread.CurrentThread.ManagedThreadId == MainThreadId;
static readonly ConcurrentQueue<Action> _actions = new ConcurrentQueue<Action>();
static MainThreadDispatcher instance = null!;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Initialize()
{
// Save the current main thread ID
MainThreadId = Thread.CurrentThread.ManagedThreadId;
if (instance != null)
return;
// Only create the dispatcher in Play mode
if (!Application.isPlaying)
return;
var obj = new GameObject("MainThreadDispatcher");
instance = obj.AddComponent<MainThreadDispatcher>();
DontDestroyOnLoad(obj);
}
#if UNITY_EDITOR
[InitializeOnLoadMethod]
static void EditorInitialize()
{
// Save the current main thread ID
MainThreadId = Thread.CurrentThread.ManagedThreadId;
if (instance != null)
UnityEngine.Object.DestroyImmediate(instance.gameObject);
UnityEditor.Compilation.CompilationPipeline.compilationFinished += OnCompilationFinished;
}
static void OnCompilationFinished(object obj) => Initialize();
#endif
public static void Enqueue(Action action) => _actions.Enqueue(action);
void Awake()
{
// Save the current main thread ID
MainThreadId = Thread.CurrentThread.ManagedThreadId;
}
void Update()
{
while (_actions.TryDequeue(out var action))
action.Invoke();
}
}
}