-
-
Notifications
You must be signed in to change notification settings - Fork 176
Expand file tree
/
Copy pathExecuteOnMainThread.cs
More file actions
61 lines (57 loc) · 1.7 KB
/
ExecuteOnMainThread.cs
File metadata and controls
61 lines (57 loc) · 1.7 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
using System;
using System.Collections;
using System.Collections.Concurrent;
using UnityEngine;
namespace Proyecto26.Helper
{
/// <summary>
/// Original solution from: https://stackoverflow.com/a/53818416/10305444
/// Should also read: https://gamedev.stackexchange.com/a/195298/126092
/// </summary>
/// <example>
/// Code here will be called in the main thread.
/// <code>
/// ExecuteOnMainThread.RunOnMainThread.Enqueue(() => {
/// // Any API call using RestClient
/// });
/// </code>
/// </example>
public class ExecuteOnMainThread : MonoBehaviour
{
private static ExecuteOnMainThread _instance;
public static ExecuteOnMainThread Instance { get { return _instance; } }
void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
/// <summary>
/// Store all instance of Action's and try to invoke them
/// </summary>
public static readonly ConcurrentQueue<Action> RunOnMainThread = new ConcurrentQueue<Action>();
/// <summary>
/// Unity's Update method
/// </summary>
void Update()
{
if (!RunOnMainThread.IsEmpty)
{
Action action;
while (RunOnMainThread.TryDequeue(out action))
{
if (action != null) {
action.Invoke();
action = null;
}
}
}
}
}
}