-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathUpdater.cs
94 lines (85 loc) · 2.33 KB
/
Updater.cs
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using UnityEngine;
namespace DvMod.RemoteDispatch
{
public class Updater : MonoBehaviour
{
public void Start()
{
StartCoroutine(CheckPlayerTransformCoro());
StartCoroutine(DeferredEventsCoro());
}
private static GameObject? rootObject;
public static void Create()
{
if (rootObject == null)
{
rootObject = new GameObject();
GameObject.DontDestroyOnLoad(rootObject);
rootObject.AddComponent<Updater>();
}
}
public static void Destroy()
{
if (rootObject != null)
{
GameObject.Destroy(rootObject);
rootObject = null;
}
}
private IEnumerator CheckPlayerTransformCoro()
{
while (true)
{
yield return WaitFor.Seconds(0.1f);
PlayerData.CheckTransform();
}
}
private IEnumerator DeferredEventsCoro()
{
while (true)
{
while (taskQueue.TryDequeue(out var action))
action();
yield return null;
}
}
private static readonly ConcurrentQueue<Action> taskQueue = new ConcurrentQueue<Action>();
public static Task RunOnMainThread(Action action)
{
var tcs = new TaskCompletionSource<bool>();
taskQueue.Enqueue(() =>
{
try
{
action();
tcs.SetResult(true);
}
catch (Exception e)
{
tcs.SetException(e);
}
});
return tcs.Task;
}
public static Task<T> RunOnMainThread<T>(Func<T> func)
{
var tcs = new TaskCompletionSource<T>();
taskQueue.Enqueue(() =>
{
try
{
tcs.SetResult(func());
}
catch (Exception e)
{
tcs.SetException(e);
}
});
return tcs.Task;
}
}
}