-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathAwaitableExtensions.cs
More file actions
480 lines (431 loc) · 18.6 KB
/
AwaitableExtensions.cs
File metadata and controls
480 lines (431 loc) · 18.6 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GameFramework;
using GameFramework.DataTable;
using GameFramework.Event;
using GameFramework.Resource;
using UnityEngine;
using UnityGameFramework.Runtime;
namespace UGFExtensions.Await
{
public static partial class AwaitableExtensions
{
private static readonly Dictionary<int, TaskCompletionSource<UIForm>> s_UIFormTcs =
new Dictionary<int, TaskCompletionSource<UIForm>>();
private static readonly Dictionary<int, TaskCompletionSource<Entity>> s_EntityTcs =
new Dictionary<int, TaskCompletionSource<Entity>>();
private static readonly Dictionary<string, TaskCompletionSource<bool>> s_DataTableTcs =
new Dictionary<string, TaskCompletionSource<bool>>();
private static readonly Dictionary<string, TaskCompletionSource<bool>> s_LoadSceneTcs =
new Dictionary<string, TaskCompletionSource<bool>>();
private static readonly Dictionary<string, TaskCompletionSource<bool>> s_UnLoadSceneTcs =
new Dictionary<string, TaskCompletionSource<bool>>();
private static readonly HashSet<int> s_WebSerialIDs = new HashSet<int>();
private static readonly List<WebResult> s_DelayReleaseWebResult = new List<WebResult>();
private static readonly HashSet<int> s_DownloadSerialIds = new HashSet<int>();
private static readonly List<DownLoadResult> s_DelayReleaseDownloadResult = new List<DownLoadResult>();
#if UNITY_EDITOR
private static bool s_IsSubscribeEvent = false;
#endif
/// <summary>
/// 注册需要的事件 (需再流程入口处调用 防止框架重启导致事件被取消问题)
/// </summary>
public static void SubscribeEvent()
{
EventComponent eventComponent = UnityGameFramework.Runtime.GameEntry.GetComponent<EventComponent>();
eventComponent.Subscribe(OpenUIFormSuccessEventArgs.EventId, OnOpenUIFormSuccess);
eventComponent.Subscribe(OpenUIFormFailureEventArgs.EventId, OnOpenUIFormFailure);
eventComponent.Subscribe(ShowEntitySuccessEventArgs.EventId, OnShowEntitySuccess);
eventComponent.Subscribe(ShowEntityFailureEventArgs.EventId, OnShowEntityFailure);
eventComponent.Subscribe(LoadSceneSuccessEventArgs.EventId, OnLoadSceneSuccess);
eventComponent.Subscribe(LoadSceneFailureEventArgs.EventId, OnLoadSceneFailure);
eventComponent.Subscribe(UnloadSceneSuccessEventArgs.EventId, OnUnloadSceneSuccess);
eventComponent.Subscribe(UnloadSceneFailureEventArgs.EventId, OnUnloadSceneFailure);
// eventComponent.Subscribe(LoadDataTableSuccessEventArgs.EventId, OnLoadDataTableSuccess);
// eventComponent.Subscribe(LoadDataTableFailureEventArgs.EventId, OnLoadDataTableFailure);
eventComponent.Subscribe(WebRequestSuccessEventArgs.EventId, OnWebRequestSuccess);
eventComponent.Subscribe(WebRequestFailureEventArgs.EventId, OnWebRequestFailure);
eventComponent.Subscribe(DownloadSuccessEventArgs.EventId, OnDownloadSuccess);
eventComponent.Subscribe(DownloadFailureEventArgs.EventId, OnDownloadFailure);
#if UNITY_EDITOR
s_IsSubscribeEvent = true;
#endif
}
#if UNITY_EDITOR
private static void TipsSubscribeEvent()
{
if (!s_IsSubscribeEvent)
{
throw new Exception("Use await/async extensions must to subscribe event!");
}
}
#endif
/// <summary>
/// 打开界面(可等待)
/// </summary>
public static Task<UIForm> OpenUIFormAsync(this UIComponent uiComponent,string uiFormAssetName, string uiGroupName, int priority, bool pauseCoveredUIForm, object userData)
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
int serialId = uiComponent.OpenUIForm(uiFormAssetName, uiGroupName, priority, pauseCoveredUIForm, userData);
var tcs = new TaskCompletionSource<UIForm>();
s_UIFormTcs.Add(serialId, tcs);
return tcs.Task;
}
private static void OnOpenUIFormSuccess(object sender, GameEventArgs e)
{
OpenUIFormSuccessEventArgs ne = (OpenUIFormSuccessEventArgs)e;
s_UIFormTcs.TryGetValue(ne.UIForm.SerialId, out TaskCompletionSource<UIForm> tcs);
if (tcs != null)
{
tcs.SetResult(ne.UIForm);
s_UIFormTcs.Remove(ne.UIForm.SerialId);
}
}
private static void OnOpenUIFormFailure(object sender, GameEventArgs e)
{
OpenUIFormFailureEventArgs ne = (OpenUIFormFailureEventArgs)e;
s_UIFormTcs.TryGetValue(ne.SerialId, out TaskCompletionSource<UIForm> tcs);
if (tcs != null)
{
Debug.LogError(ne.ErrorMessage);
tcs.SetException(new GameFrameworkException(ne.ErrorMessage));
s_UIFormTcs.Remove(ne.SerialId);
}
}
/// <summary>
/// 显示实体(可等待)
/// </summary>
public static Task<Entity> ShowEntityAsync(this EntityComponent entityComponent, int entityId,
Type entityLogicType, string entityAssetName, string entityGroupName, int priority,object userData)
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
var tcs = new TaskCompletionSource<Entity>();
s_EntityTcs.Add(entityId, tcs);
entityComponent.ShowEntity(entityId, entityLogicType, entityAssetName, entityGroupName, priority, userData);
return tcs.Task;
}
private static void OnShowEntitySuccess(object sender, GameEventArgs e)
{
ShowEntitySuccessEventArgs ne = (ShowEntitySuccessEventArgs)e;
s_EntityTcs.TryGetValue(ne.Entity.Id, out var tcs);
if (tcs != null)
{
tcs.SetResult(ne.Entity);
s_EntityTcs.Remove(ne.Entity.Id);
}
}
private static void OnShowEntityFailure(object sender, GameEventArgs e)
{
ShowEntityFailureEventArgs ne = (ShowEntityFailureEventArgs)e;
s_EntityTcs.TryGetValue(ne.EntityId, out var tcs);
if (tcs != null)
{
Debug.LogError(ne.ErrorMessage);
tcs.SetException(new GameFrameworkException(ne.ErrorMessage));
s_EntityTcs.Remove(ne.EntityId);
}
}
/// <summary>
/// 加载场景(可等待)
/// </summary>
public static async Task<bool> LoadSceneAsync(this SceneComponent sceneComponent, string sceneAssetName)
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
var tcs = new TaskCompletionSource<bool>();
var isUnLoadScene = s_UnLoadSceneTcs.TryGetValue(sceneAssetName, out var unloadSceneTcs);
if (isUnLoadScene)
{
await unloadSceneTcs.Task;
}
s_LoadSceneTcs.Add(sceneAssetName, tcs);
try
{
sceneComponent.LoadScene(sceneAssetName);
}
catch (Exception e)
{
Debug.LogError(e.ToString());
tcs.SetException(e);
s_LoadSceneTcs.Remove(sceneAssetName);
}
return await tcs.Task;
}
private static void OnLoadSceneSuccess(object sender, GameEventArgs e)
{
LoadSceneSuccessEventArgs ne = (LoadSceneSuccessEventArgs)e;
s_LoadSceneTcs.TryGetValue(ne.SceneAssetName, out var tcs);
if (tcs != null)
{
tcs.SetResult(true);
s_LoadSceneTcs.Remove(ne.SceneAssetName);
}
}
private static void OnLoadSceneFailure(object sender, GameEventArgs e)
{
LoadSceneFailureEventArgs ne = (LoadSceneFailureEventArgs)e;
s_LoadSceneTcs.TryGetValue(ne.SceneAssetName, out var tcs);
if (tcs != null)
{
Debug.LogError(ne.ErrorMessage);
tcs.SetException(new GameFrameworkException(ne.ErrorMessage));
s_LoadSceneTcs.Remove(ne.SceneAssetName);
}
}
/// <summary>
/// 卸载场景(可等待)
/// </summary>
public static async Task<bool> UnLoadSceneAsync(this SceneComponent sceneComponent, string sceneAssetName)
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
var tcs = new TaskCompletionSource<bool>();
var isLoadSceneTcs = s_LoadSceneTcs.TryGetValue(sceneAssetName, out var loadSceneTcs);
if (isLoadSceneTcs)
{
Debug.Log("Unload loading scene");
await loadSceneTcs.Task;
}
s_UnLoadSceneTcs.Add(sceneAssetName, tcs);
try
{
sceneComponent.UnloadScene(sceneAssetName);
}
catch (Exception e)
{
Debug.LogError(e.ToString());
tcs.SetException(e);
s_UnLoadSceneTcs.Remove(sceneAssetName);
}
return await tcs.Task;
}
private static void OnUnloadSceneSuccess(object sender, GameEventArgs e)
{
UnloadSceneSuccessEventArgs ne = (UnloadSceneSuccessEventArgs)e;
s_UnLoadSceneTcs.TryGetValue(ne.SceneAssetName, out var tcs);
if (tcs != null)
{
tcs.SetResult(true);
s_UnLoadSceneTcs.Remove(ne.SceneAssetName);
}
}
private static void OnUnloadSceneFailure(object sender, GameEventArgs e)
{
UnloadSceneFailureEventArgs ne = (UnloadSceneFailureEventArgs)e;
s_UnLoadSceneTcs.TryGetValue(ne.SceneAssetName, out var tcs);
if (tcs != null)
{
Debug.LogError($"Unload scene {ne.SceneAssetName} failure.");
tcs.SetException(new GameFrameworkException($"Unload scene {ne.SceneAssetName} failure."));
s_UnLoadSceneTcs.Remove(ne.SceneAssetName);
}
}
/// <summary>
/// 加载资源(可等待)
/// </summary>
public static Task<T> LoadAssetAsync<T>(this ResourceComponent resourceComponent, string assetName)
where T : UnityEngine.Object
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
TaskCompletionSource<T> loadAssetTcs = new TaskCompletionSource<T>();
resourceComponent.LoadAsset(assetName, typeof(T), new LoadAssetCallbacks(
(tempAssetName, asset, duration, userdata) =>
{
var source = loadAssetTcs;
loadAssetTcs = null;
T tAsset = asset as T;
if (tAsset != null)
{
source.SetResult(tAsset);
}
else
{
Debug.LogError($"Load asset failure load type is {asset.GetType()} but asset type is {typeof(T)}.");
source.SetException(new GameFrameworkException(
$"Load asset failure load type is {asset.GetType()} but asset type is {typeof(T)}."));
}
},
(tempAssetName, status, errorMessage, userdata) =>
{
Debug.LogError(errorMessage);
loadAssetTcs.SetException(new GameFrameworkException(errorMessage));
}
));
return loadAssetTcs.Task;
}
/// <summary>
/// 加载多个资源(可等待)
/// </summary>
public static async Task<T[]> LoadAssetsAsync<T>(this ResourceComponent resourceComponent, string[] assetName) where T : UnityEngine.Object
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
if (assetName == null)
{
return null;
}
T[] assets = new T[assetName.Length];
Task<T>[] tasks = new Task<T>[assets.Length];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = resourceComponent.LoadAssetAsync<T>(assetName[i]);
}
await Task.WhenAll(tasks);
for (int i = 0; i < assets.Length; i++)
{
assets[i] = tasks[i].Result;
}
return assets;
}
/// <summary>
/// 增加Web请求任务(可等待)
/// </summary>
public static Task<WebResult> AddWebRequestAsync(this WebRequestComponent webRequestComponent,
string webRequestUri, WWWForm wwwForm = null, object userdata = null)
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
var tsc = new TaskCompletionSource<WebResult>();
int serialId = webRequestComponent.AddWebRequest(webRequestUri, wwwForm,
AwaitDataWrap<WebResult>.Create(userdata, tsc));
s_WebSerialIDs.Add(serialId);
return tsc.Task;
}
/// <summary>
/// 增加Web请求任务(可等待)
/// </summary>
public static Task<WebResult> AddWebRequestAsync(this WebRequestComponent webRequestComponent,
string webRequestUri, byte[] postData, object userdata = null)
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
var tsc = new TaskCompletionSource<WebResult>();
int serialId = webRequestComponent.AddWebRequest(webRequestUri, postData,
AwaitDataWrap<WebResult>.Create(userdata, tsc));
s_WebSerialIDs.Add(serialId);
return tsc.Task;
}
private static void OnWebRequestSuccess(object sender, GameEventArgs e)
{
WebRequestSuccessEventArgs ne = (WebRequestSuccessEventArgs)e;
if (s_WebSerialIDs.Contains(ne.SerialId))
{
if (ne.UserData is AwaitDataWrap<WebResult> webRequestUserdata)
{
WebResult result = WebResult.Create(ne.GetWebResponseBytes(), false, string.Empty,
webRequestUserdata.UserData);
s_DelayReleaseWebResult.Add(result);
webRequestUserdata.Source.TrySetResult(result);
ReferencePool.Release(webRequestUserdata);
}
s_WebSerialIDs.Remove(ne.SerialId);
if (s_WebSerialIDs.Count == 0)
{
for (int i = 0; i < s_DelayReleaseWebResult.Count; i++)
{
ReferencePool.Release(s_DelayReleaseWebResult[i]);
}
s_DelayReleaseWebResult.Clear();
}
}
}
private static void OnWebRequestFailure(object sender, GameEventArgs e)
{
WebRequestFailureEventArgs ne = (WebRequestFailureEventArgs)e;
if (s_WebSerialIDs.Contains(ne.SerialId))
{
if (ne.UserData is AwaitDataWrap<WebResult> webRequestUserdata)
{
WebResult result = WebResult.Create(null, true, ne.ErrorMessage, webRequestUserdata.UserData);
webRequestUserdata.Source.TrySetResult(result);
s_DelayReleaseWebResult.Add(result);
ReferencePool.Release(webRequestUserdata);
}
s_WebSerialIDs.Remove(ne.SerialId);
if (s_WebSerialIDs.Count == 0)
{
for (int i = 0; i < s_DelayReleaseWebResult.Count; i++)
{
ReferencePool.Release(s_DelayReleaseWebResult[i]);
}
s_DelayReleaseWebResult.Clear();
}
}
}
/// <summary>
/// 增加下载任务(可等待)
/// </summary>
public static Task<DownLoadResult> AddDownloadAsync(this DownloadComponent downloadComponent,
string downloadPath,
string downloadUri,
object userdata = null)
{
#if UNITY_EDITOR
TipsSubscribeEvent();
#endif
var tcs = new TaskCompletionSource<DownLoadResult>();
int serialId = downloadComponent.AddDownload(downloadPath, downloadUri,
AwaitDataWrap<DownLoadResult>.Create(userdata, tcs));
s_DownloadSerialIds.Add(serialId);
return tcs.Task;
}
private static void OnDownloadSuccess(object sender, GameEventArgs e)
{
DownloadSuccessEventArgs ne = (DownloadSuccessEventArgs)e;
if (s_DownloadSerialIds.Contains(ne.SerialId))
{
if (ne.UserData is AwaitDataWrap<DownLoadResult> awaitDataWrap)
{
DownLoadResult result = DownLoadResult.Create(false, string.Empty, awaitDataWrap.UserData);
s_DelayReleaseDownloadResult.Add(result);
awaitDataWrap.Source.TrySetResult(result);
ReferencePool.Release(awaitDataWrap);
}
s_DownloadSerialIds.Remove(ne.SerialId);
if (s_DownloadSerialIds.Count == 0)
{
for (int i = 0; i < s_DelayReleaseDownloadResult.Count; i++)
{
ReferencePool.Release(s_DelayReleaseDownloadResult[i]);
}
s_DelayReleaseDownloadResult.Clear();
}
}
}
private static void OnDownloadFailure(object sender, GameEventArgs e)
{
DownloadFailureEventArgs ne = (DownloadFailureEventArgs)e;
if (s_DownloadSerialIds.Contains(ne.SerialId))
{
if (ne.UserData is AwaitDataWrap<DownLoadResult> awaitDataWrap)
{
DownLoadResult result = DownLoadResult.Create(true, ne.ErrorMessage, awaitDataWrap.UserData);
s_DelayReleaseDownloadResult.Add(result);
awaitDataWrap.Source.TrySetResult(result);
ReferencePool.Release(awaitDataWrap);
}
s_DownloadSerialIds.Remove(ne.SerialId);
if (s_DownloadSerialIds.Count == 0)
{
for (int i = 0; i < s_DelayReleaseDownloadResult.Count; i++)
{
ReferencePool.Release(s_DelayReleaseDownloadResult[i]);
}
s_DelayReleaseDownloadResult.Clear();
}
}
}
}
}