Created
April 20, 2024 17:38
-
-
Save ShutovKS/acc89da3dc2065548f5816fb911e9955 to your computer and use it in GitHub Desktop.
Unity main thread manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using UnityEngine; | |
public class UnityMainThreadManager : MonoBehaviour | |
{ | |
private static readonly Queue<Action> executionQueue = new(); | |
private static UnityMainThreadManager _instance; | |
public static UnityMainThreadManager Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
var instance = new GameObject("UnityMainThreadManager"); | |
DontDestroyOnLoad(instance); | |
_instance = instance.AddComponent<UnityMainThreadManager>(); | |
} | |
return _instance; | |
} | |
} | |
public void Update() | |
{ | |
lock (executionQueue) | |
{ | |
while (executionQueue.Count > 0) | |
{ | |
executionQueue.Dequeue().Invoke(); | |
} | |
} | |
} | |
public void Enqueue(IEnumerator action) | |
{ | |
lock (executionQueue) | |
{ | |
executionQueue.Enqueue(() => StartCoroutine(action)); | |
} | |
} | |
public void Enqueue(Func<Task> asyncAction) | |
{ | |
Enqueue(ToCoroutine(asyncAction)); | |
} | |
public void Enqueue(Action action) | |
{ | |
Enqueue(ActionWrapper(action)); | |
} | |
private static IEnumerator ToCoroutine(Func<Task> asyncAction) | |
{ | |
asyncAction().Wait(); | |
yield return null; | |
} | |
private static IEnumerator ActionWrapper(Action action) | |
{ | |
action?.Invoke(); | |
yield return null; | |
} | |
private void OnDestroy() | |
{ | |
_instance = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment