UniTask
===
[![GitHub Actions](https://github.com/Cysharp/UniTask/workflows/Build-Debug/badge.svg)](https://github.com/Cysharp/UniTask/actions) [![Releases](https://img.shields.io/github/release/Cysharp/UniTask.svg)](https://github.com/Cysharp/UniTask/releases)
Provides an efficient allocation free async/await integration for Unity.
* Struct based `UniTask<T>` and custom AsyncMethodBuilder to achieve zero allocation
* Makes all Unity AsyncOperations and Coroutines awaitable
* PlayerLoop based task(`UniTask.Yield`, `UniTask.Delay`, `UniTask.DelayFrame`, etc..) that enable replacing all coroutine operations
* MonoBehaviour Message Events and uGUI Events as awaitable/async-enumerable
* Runs completely on Unity's PlayerLoop so doesn't use threads and runs on WebGL, wasm, etc.
* Asynchronous LINQ, with Channel and AsyncReactiveProperty
* TaskTracker window to prevent memory leaks
* Highly compatible behaviour with Task/ValueTask/IValueTaskSource
For technical details, see blog post: [UniTask v2 — Zero Allocation async/await for Unity, with Asynchronous LINQ
](https://medium.com/@neuecc/unitask-v2-zero-allocation-async-await-for-unity-with-asynchronous-linq-1aa9c96aa7dd)
For advanced tips, see blog post: [Extends UnityWebRequest via async decorator pattern — Advanced Techniques of UniTask](https://medium.com/@neuecc/extends-unitywebrequest-via-async-decorator-pattern-advanced-techniques-of-unitask-ceff9c5ee846)
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Getting started](#getting-started)
- [Basics of UniTask and AsyncOperation](#basics-of-unitask-and-asyncoperation)
- [Cancellation and Exception handling](#cancellation-and-exception-handling)
- [Timeout handling](#timeout-handling)
- [Progress](#progress)
- [PlayerLoop](#playerloop)
- [async void vs async UniTaskVoid](#async-void-vs-async-unitaskvoid)
- [UniTaskTracker](#unitasktracker)
- [External Assets](#external-assets)
- [AsyncEnumerable and Async LINQ](#asyncenumerable-and-async-linq)
- [Awaitable Events](#awaitable-events)
- [Channel](#channel)
- [For Unit Testing](#for-unit-testing)
- [ThreadPool limitation](#threadpool-limitation)
- [IEnumerator.ToUniTask limitation](#ienumeratortounitask-limitation)
- [For UnityEditor](#for-unityeditor)
- [Compare with Standard Task API](#compare-with-standard-task-api)
- [Pooling Configuration](#pooling-configuration)
- [Allocation on Profiler](#allocation-on-profiler)
- [UniTaskSynchronizationContext](#unitasksynchronizationcontext)
- [API References](#api-references)
- [UPM Package](#upm-package)
- [Install via git URL](#install-via-git-url)
- [Install via OpenUPM](#install-via-openupm)
- [.NET Core](#net-core)
- [License](#license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
Getting started
---
Install via [UPM package](#upm-package) or asset package(`UniTask.*.*.*.unitypackage`) available in [UniTask/releases](https://github.com/Cysharp/UniTask/releases) page.
```csharp
// extension awaiter/methods can be used by this namespace
using Cysharp.Threading.Tasks;
// You can return type as struct UniTask<T>(or UniTask), it is unity specialized lightweight alternative of Task<T>
// zero allocation and fast excution for zero overhead async/await integrate with Unity
async UniTask<string> DemoAsync()
{
// You can await Unity's AsyncObject
var asset = await Resources.LoadAsync<TextAsset>("foo");
var txt = (await UnityWebRequest.Get("https://...").SendWebRequest()).downloadHandler.text;
await SceneManager.LoadSceneAsync("scene2");
// .WithCancellation enables Cancel, GetCancellationTokenOnDestroy synchornizes with lifetime of GameObject
var asset2 = await Resources.LoadAsync<TextAsset>("bar").WithCancellation(this.GetCancellationTokenOnDestroy());
// .ToUniTask accepts progress callback(and all options), Progress.Create is a lightweight alternative of IProgress<T>
var asset3 = await Resources.LoadAsync<TextAsset>("baz").ToUniTask(Progress.Create<float>(x => Debug.Log(x)));
// await frame-based operation like a coroutine
await UniTask.DelayFrame(100);
// replacement of yield return new WaitForSeconds/WaitForSecondsRealtime
await UniTask.Delay(TimeSpan.FromSeconds(10), ignoreTimeScale: false);
// yield any playerloop timing(PreUpdate, Update, LateUpdate, etc...)
await UniTask.Yield(PlayerLoopTiming.PreLateUpdate);
// replacement of yield return null
await UniTask.Yield();
await UniTask.NextFrame();
// replacement of WaitForEndOfFrame(requires MonoBehaviour(CoroutineRunner))
await UniTask.WaitForEndOfFrame(this); // this is MonoBehaviour
// replacement of yield return new WaitForFixedUpdate(same as UniTask.Yield(PlayerLoopTiming.FixedUpdate))
await UniTask.WaitForFixedUpdate();
// replacement of yield return WaitUntil
await UniTask.WaitUntil(() => isActive == false);
// special helper of WaitUntil
await UniTask.WaitUntilValueChanged(this, x => x.isActive);
// You can await IEnumerator coroutines
await FooCoroutineEnumerator();
// You can await a standard task
await Task.Run(() => 100);
// Multithreading, run on ThreadPool under this code
await UniTask.SwitchToThreadPool();
/* work on ThreadPool */
// return to MainThread(same as `ObserveOnMainThread` in UniRx)
await UniTask.SwitchToMainThread();
// get async webrequest
async UniTask<string> GetTextAsync(UnityWebRequest req)
{
var op = await req.SendWebRequest();
return op.downloadHandler.text;
}
var task1 = GetTextAsync(UnityWebRequest.Get("http://google.com"));
var task2 = GetTextAsync(UnityWebRequest.Get("http://bing.com"));
var task3 = GetTextAsync(UnityWebRequest.Get("http://yahoo.com"));
// concurrent async-wait and get results easily by tuple syntax
var (google, bing, yahoo) = await UniTask.WhenAll(task1, task2, task3);
// shorthand of WhenAll, tuple can await directly
var (google2, bing2, yahoo2) = await (task1, task2, task3);
// return async-value.(or you can use `UniTask`(no result), `UniTaskVoid`(fire and forget)).
return (asset as TextAsset)?.text ?? throw new InvalidOperationException("Asset not found");
}
```
Basics of UniTask and AsyncOperation
---
UniTask features rely on C# 7.0([task-like custom async method builder feature](https://github.com/dotnet/roslyn/blob/master/docs/features/task-types.md)) so the required Unity version is after `Unity 2018.3`, the official lowest version supported is `Unity 2018.4.13f1`.
Why is UniTask(custom task-like object) required? Because Task is too heavy and not matched to Unity threading (single-thread). UniTask does not use threads and SynchronizationContext/ExecutionContext because Unity's asynchronous object is automaticaly dispatched by Unity's engine layer. It achieves faster and lower allocation, and is completely integrated with Unity.
You can await `AsyncOperation`, `ResourceRequest`, `AssetBundleRequest`, `AssetBundleCreateRequest`, `UnityWebRequestAsyncOperation`, `AsyncGPUReadbackRequest`, `IEnumerator` and others when `using Cysharp.Threading.Tasks;`.
UniTask provides three pattern of extension methods.
```csharp
* await asyncOperation;
* .WithCancellation(CancellationToken);
* .ToUniTask(IProgress, PlayerLoopTiming, CancellationToken);
```
`WithCancellation` is a simple version of `ToUniTask`, both return `UniTask`. For details of cancellation, see: [Cancellation and Exception handling](#cancellation-and-exception-handling) section.
> Note: await directly is returned from native timing of PlayerLoop but WithCancellation and ToUniTask are returned from specified PlayerLoopTiming. For details of timing, see: [PlayerLoop](#playerloop) section.
> Note: AssetBundleRequest has `asset` and `allAssets`, default await returns `asset`. If you want to
没有合适的资源?快使用搜索试试~ 我知道了~
UniTask-master插件包
共492个文件
meta:221个
cs:208个
asset:20个
0 下载量 76 浏览量
2024-03-14
18:01:12
上传
评论
收藏 492KB ZIP 举报
温馨提示
解压到工程目录下, 并在工程目录下的[Packages]文件夹中的[manifest.json]中添加["com.cysharp.unitask": "file:../LocalPackages/UniTask-master/src/UniTask/Assets/Plugins/UniTask/",]即可
资源推荐
资源详情
资源评论
收起资源包目录
UniTask-master插件包 (492个子文件)
UniTask.asmdef 1KB
UniTask.Tests.Editor.asmdef 619B
UniTask.Tests.asmdef 589B
UniTask.Addressables.asmdef 537B
UniTask.TextMeshPro.asmdef 531B
UniTask.DOTween.asmdef 521B
UniTask.Editor.asmdef 368B
RuntimeUnitTestToolkit.asmdef 367B
TempAsm.asmdef 350B
UniTask.Linq.asmdef 343B
ProjectSettings.asset 18KB
InputManager.asset 6KB
QualitySettings.asset 5KB
GraphicsSettings.asset 2KB
Physics2DSettings.asset 2KB
NavMeshAreas.asset 1KB
EditorSettings.asset 1KB
DynamicsManager.asset 1KB
PackageManagerSettings.asset 1003B
UnityConnectSettings.asset 853B
TagManager.asset 378B
EditorBuildSettings.asset 363B
AudioManager.asset 360B
TimeManager.asset 195B
VersionControlSettings.asset 188B
XRSettings.asset 158B
VFXManager.asset 157B
NetworkManager.asset 151B
PresetManager.asset 120B
ClusterInputManager.asset 114B
CombineLatest.cs 431KB
UniTask.WhenAll.Generated.cs 207KB
UniTask.WhenAny.Generated.cs 200KB
MonoBehaviourMessagesTriggers.cs 147KB
MinMax.cs 118KB
Average.cs 51KB
GroupBy.cs 44KB
Sum.cs 43KB
SelectMany.cs 38KB
UnityAsyncExtensions.cs 33KB
UniTask.Delay.cs 31KB
UnityAsyncExtensions.uGUI.cs 30KB
Join.cs 30KB
Where.cs 29KB
UniTaskExtensions.cs 29KB
UniTaskCompletionSource.cs 29KB
Select.cs 28KB
UnitTestRunner.cs 27KB
GroupJoin.cs 27KB
DistinctUntilChanged.cs 26KB
OrderBy.cs 26KB
SandboxMain.cs 26KB
UnitTestBuilder.cs 24KB
ToLookup.cs 24KB
Subscribe.cs 22KB
PlayerLoopHelper.cs 21KB
CompletionSourceTest.cs 21KB
Zip.cs 21KB
UniTask.cs 20KB
UniTaskObservableExtensions.cs 20KB
AsyncReactiveProperty.cs 20KB
UniTask.WaitUntil.cs 19KB
Aggregate.cs 19KB
MiddlewareSample.cs 18KB
TriggerEventTest.cs 18KB
Projection.cs 18KB
DOTweenAsyncExtensions.cs 18KB
Channel.cs 15KB
UniTask.Factory.cs 15KB
AsyncTest.cs 15KB
UniTask.Threading.cs 14KB
SkipWhile.cs 14KB
ToDictionary.cs 14KB
Sort.cs 14KB
AddressablesAsyncExtensions.cs 13KB
Aggregate.cs 13KB
ChannelTest.cs 13KB
TakeWhile.cs 13KB
UniTaskExtensions.Shorthand.cs 13KB
TextMeshProAsyncExtensions.InputField.cs 12KB
AsyncTestEditor.cs 12KB
UniTask.WhenAny.cs 11KB
UniTask.Run.cs 11KB
Buffer.cs 11KB
Paging.cs 11KB
FirstLast.cs 11KB
UnitTestBuilder.MenuItems.cs 11KB
Timer.cs 11KB
ToUniTaskAsyncEnumerable.cs 11KB
AsyncEnumeratorBase.cs 11KB
Distinct.cs 11KB
UnityEqualityComparer.cs 11KB
Joins.cs 11KB
StateMachineRunner.cs 10KB
EnumeratorAsyncExtensions.cs 10KB
Do.cs 10KB
WeakDictionary.cs 9KB
EveryValueChanged.cs 9KB
DiagnosticsExtensions.cs 9KB
AsyncTriggerBase.cs 9KB
共 492 条
- 1
- 2
- 3
- 4
- 5
资源评论
ViYeye
- 粉丝: 40
- 资源: 1
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功