unity5提供了协程,不过用起来很蛋疼,当然如果是unity2017 你就可以用async await了

提供一个TaskManager来封装协程(github  https://github.com/krockot/Unity-TaskManager)

1.TaskManager

/// TaskManager.cs
/// Copyright (c) 2011, Ken Rockot <k-e-n-@-REMOVE-CAPS-AND-HYPHENS-oz.gs>. All rights reserved.
/// Everyone is granted non-exclusive license to do anything at all with this code.
///
/// This is a new coroutine interface for Unity.
///
/// The motivation for this is twofold:
///
/// 1. The existing coroutine API provides no means of stopping specific
/// coroutines; StopCoroutine only takes a string argument, and it stops
/// all coroutines started with that same string; there is no way to stop
/// coroutines which were started directly from an enumerator. This is
/// not robust enough and is also probably pretty inefficient.
///
/// 2. StartCoroutine and friends are MonoBehaviour methods. This means
/// that in order to start a coroutine, a user typically must have some
/// component reference handy. There are legitimate cases where such a
/// constraint is inconvenient. This implementation hides that
/// constraint from the user.
///
/// Example usage:
///
/// ----------------------------------------------------------------------------
/// IEnumerator MyAwesomeTask()
/// {
/// while(true) {
/// Debug.Log("Logcat iz in ur consolez, spammin u wif messagez.");
/// yield return null;
//// }
/// }
///
/// IEnumerator TaskKiller(float delay, Task t)
/// {
/// yield return new WaitForSeconds(delay);
/// t.Stop();
/// }
///
/// void SomeCodeThatCouldBeAnywhereInTheUniverse()
/// {
/// Task spam = new Task(MyAwesomeTask());
/// new Task(TaskKiller(5, spam));
/// }
/// ----------------------------------------------------------------------------
///
/// When SomeCodeThatCouldBeAnywhereInTheUniverse is called, the debug console
/// will be spammed with annoying messages for 5 seconds.
///
/// Simple, really. There is no need to initialize or even refer to TaskManager.
/// When the first Task is created in an application, a "TaskManager" GameObject
/// will automatically be added to the scene root with the TaskManager component
/// attached. This component will be responsible for dispatching all coroutines
/// behind the scenes.
///
/// Task also provides an event that is triggered when the coroutine exits. using UnityEngine;
using System.Collections; /// A Task object represents a coroutine. Tasks can be started, paused, and stopped.
/// It is an error to attempt to start a task that has been stopped or which has
/// naturally terminated.
public class Task
{
/// Returns true if and only if the coroutine is running. Paused tasks
/// are considered to be running.
public bool Running
{
get
{
return task.Running;
}
} /// Returns true if and only if the coroutine is currently paused.
public bool Paused
{
get
{
return task.Paused;
}
} /// Delegate for termination subscribers. manual is true if and only if
/// the coroutine was stopped with an explicit call to Stop().
public delegate void FinishedHandler(bool manual); /// Termination event. Triggered when the coroutine completes execution.
public event FinishedHandler Finished; /// Creates a new Task object for the given coroutine.
///
/// If autoStart is true (default) the task is automatically started
/// upon construction.
public Task(IEnumerator c, bool autoStart = true)
{
task = TaskManager.CreateTask(c);
task.Finished += TaskFinished;
if (autoStart)
Start();
} /// Begins execution of the coroutine
public void Start()
{
task.Start();
} /// Discontinues execution of the coroutine at its next yield.
public void Stop()
{
task.Stop();
} public void Pause()
{
task.Pause();
} public void Unpause()
{
task.Unpause();
} void TaskFinished(bool manual)
{
FinishedHandler handler = Finished;
if (handler != null)
handler(manual);
} TaskManager.TaskState task;
} class TaskManager : MonoBehaviour
{
public class TaskState
{
public bool Running
{
get
{
return running;
}
} public bool Paused
{
get
{
return paused;
}
} public delegate void FinishedHandler(bool manual);
public event FinishedHandler Finished; IEnumerator coroutine;
bool running;
bool paused;
bool stopped; public TaskState(IEnumerator c)
{
coroutine = c;
} public void Pause()
{
paused = true;
} public void Unpause()
{
paused = false;
} public void Start()
{
running = true;
singleton.StartCoroutine(CallWrapper());
} public void Stop()
{
stopped = true;
running = false;
} IEnumerator CallWrapper()
{
yield return null;
IEnumerator e = coroutine;
while (running)
{
if (paused)
yield return null;
else
{
if (e != null && e.MoveNext())
{
yield return e.Current;
}
else
{
running = false;
}
}
} FinishedHandler handler = Finished;
if (handler != null)
handler(stopped);
}
} static TaskManager singleton; public static TaskState CreateTask(IEnumerator coroutine)
{
if (singleton == null)
{
GameObject go = new GameObject("TaskManager");
singleton = go.AddComponent<TaskManager>();
}
return new TaskState(coroutine);
}
}

2.使用说明

using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class Test : MonoBehaviour { // Use this for initialization
void Start () {
TaskManager.TaskState task = TaskManager.CreateTask(MyC());
//然后单独操作这个task就行了,很方便
task.Start();//任务开始
task.Finished += Task_Finished;//完成回调
task.Stop();//任务停止
task.Pause();//任务暂停
task.Unpause();//任务恢复
} private void Task_Finished(bool manual)
{
Debug.Log("任务完成");
} IEnumerator MyC()
{
yield return new WaitForSeconds();
Debug.Log("hahahhhh");
} }

封装你的协程Unity TaskManager的更多相关文章

  1. 聊一聊Unity协程背后的实现原理

    Unity开发不可避免的要用到协程(Coroutine),协程同步代码做异步任务的特性使程序员摆脱了曾经异步操作加回调的编码方式,使代码逻辑更加连贯易读.然而在惊讶于协程的好用与神奇的同时,因为不清楚 ...

  2. python学习笔记-(十四)进程&协程

    一. 进程 1. 多进程multiprocessing multiprocessing包是Python中的多进程管理包,是一个跨平台版本的多进程模块.与threading.Thread类似,它可以利用 ...

  3. Python开发【第九章】:线程、进程和协程

    一.线程 线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务 1.t ...

  4. Python 协程了解

    协程: 1.协程,又称微线程,纤程.英文名Coroutine. 2.协程是跑在线程内的单线程,串行没有锁. 3.协程是一种用户态的轻量级线程. 4.协程CPU是访问不到的,协程是用户自己控制的.   ...

  5. Python全栈开发-Day10-进程/协程/异步IO/IO多路复用

    本节内容 多进程multiprocessing 进程间的通讯 协程 论事件驱动与异步IO Select\Poll\Epoll——IO多路复用   1.多进程multiprocessing Python ...

  6. C高级 跨平台协程库

    1.0 协程库引言 协程对于上层语言还是比较常见的. 例如C# 中 yield retrun, lua 中 coroutine.yield 等来构建同步并发的程序. 本文就是探讨如何从底层实现开发级别 ...

  7. Python学习笔记整理总结【网络编程】【线程/进程/协程/IO多路模型/select/poll/epoll/selector】

    一.socket(单链接) 1.socket:应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socke ...

  8. python-进程、线程与协程

    基础概念 进程 是一个执行中的程序,即将程序装载到内存中,系统为它分配资源的这一过程.进程是操作系统资源分配的基本单位. 每一个进程都有它自己的地址空间,一般情况下,包括文本区域(text regio ...

  9. 协程分析之context上下文切换

    协程现在已经不是个新东西了,很多语言都提供了原生支持,也有很多开源的库也提供了协程支持. 最近为了要给tbox增加协程,特地研究了下各大开源协程库的实现,例如:libtask, libmill, bo ...

随机推荐

  1. linux 挂载和使用文件系统

    从分区,到创建文件系统,再到把磁盘或分区挂载到一个目录后才能够使用. Windows或Mac系统会自动进行挂载,一旦创建好文件系统后会自动挂载到系统上,Windows我们称之为C\D盘,而Linux需 ...

  2. linux安装redis及phpredis环境配置

    下载安装包 cd /home/redis/tar wget http://redis.googlecode.com/files/redis-2.4.17.tar.gz tar zxvf redis-2 ...

  3. [修正] Firemonkey 中英文混排折行,省略字符,首字避开标点

    问题:FMX 在移动平台的文字显示并非由该平台的原生 API 来显示,而是由 FMX.TextLayout.GPU 来处理,也许是官方没留意到中文字符的问题,造成在中英文混排折行时,有些问题. 修正: ...

  4. Ubuntu 网关服务器配置

    1.设置Linux内核支持ip数据包的转发 echo "1" > /proc/sys/net/ipv4/ip_forward or vi /etc/sysctl.conf   ...

  5. Wait--常见的等待类型

    --==================================================================================--SLEEP_BPOOL_FL ...

  6. [VSTO] warning CS0467 解决方案

    warning CS0467: Ambiguity between method 'Microsoft.Office.Interop.Word._Document.Close(ref object, ...

  7. leetcode 两个数组的交集 II

    给定两个数组,写一个方法来计算它们的交集. 例如: 给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2]. /** * @param {number[] ...

  8. C#多线程编程实战1.1创建线程

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...

  9. 使用 dlv 调试go 程序

    目录 使用 dlv 调试smartraiden 一 正常启动 smartraiden 二 dlv 调试 三 dlv attach 使用 dlv 调试smartraiden by 白振轩 使用 dlv ...

  10. nowcoder(牛客网)提高组模拟赛第四场 解题报告

    T1 动态点分治 就是模拟..... 但是没有过!! 看了题解之后发现.... 坑点:有可能 \(x<=r\),但是