Skip to content

The unity3d coroutine tool collections.一个Unity3D的协程工具集封装(协程池,无GC优化等)

Notifications You must be signed in to change notification settings

keekekx/CoroutineHelper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 

Repository files navigation

CoroutineHelper

CoroutineHelper is a unity3d coroutine tool collections.
协程助手是一个Unity3D的协程工具集。

Common:

Non-MonoBehaviour class start coroutine
你可以给非MonoBehaviour类开启协程

CoroutineHelper.StartCoroutine(...)

And packaged some common extensions
并且封装了一些常用扩展

CoroutineHelper.DelayInvoke(() => Debug.Log("foo!"), 2f);
CoroutineHelper.DelayNextFrameInvoke(() => Debug.Log("foo!"));

CoroutineGroup:

or like the MonoBehaviour class, you can ‘StopAllCoroutine’ through CoroutineGroup
或者像MonoBehaviour类一样,你可以用StopAllCoroutine来关闭当前Mono运行的所有协程通过协程组

void Test()
{
    var coroutineGroup = CoroutineHelper.Factory.CreateCoroutineGroup();
    coroutineGroup.StartCoroutine(Foo());
    coroutineGroup.StartCoroutine(Foo());
    coroutineGroup.StartCoroutine(Foo());
    coroutineGroup.StartCoroutine(Foo());

    coroutineGroup.StopAllCoroutines();
}

IEnumerator Foo() { yield break; }

CoroutinePool:

You can also create a coroutine pool to avoid the GC of StartCoroutine, but the coroutine pool is more troublesome to use.
你还可以创建协程池来避免StartCoroutine的GC问题,但是这个用起来会复杂一些。

var coroutinePool = CoroutineHelper.Factory.CreateCoroutinePool(10);
coroutinePool.TryStartCoroutineInPool(Foo());//If pool is full, execute it immediately with StartCoroutine.

if (coroutinePool.HasCoroutineIdle)
    coroutinePool.StartCoroutine(Foo());//Or like this.

InternalPool:

and you can avoid GC with some internal pools.
另外还封装了一些yield函数的内部池,避免诸如new WaitForSeconds(...)带来的GC开销。

IEnumerator Foo()
{
    yield return new WaitForSeconds(1f);//wait 1 sec, has GC.

    var waitForSeconds = CoroutineHelper.Pool_WaitForSeconds.Spawn();
    yield return waitForSeconds.Reset(1f);
    CoroutineHelper.Pool_WaitForSeconds.Despawn(waitForSeconds);//wait 1 sec with CoroutineHelper, no GC.
}

Statistics:

Finally, there is a counting function to troubleshoot leaks.
最后,还有一个计数功能,来排查泄露问题

void OnGUI()
{
    GUILayout.Box("Coroutine Count: " + CoroutineHelper.CoroutineCount);
    GUILayout.Box("Pool Total Size: " + CoroutineHelper.PoolTotalSize);
}

About

The unity3d coroutine tool collections.一个Unity3D的协程工具集封装(协程池,无GC优化等)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages