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. hdu2579之BFS

    Dating with girls(2) Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Oth ...

  2. cenos7切换阿里源

    备份并安装base reop源 cd /etc/yum.repos.d sudo mv CentOS-Base.repo CentOS-Base.repo.bak 下载阿里源并配置 sudo wget ...

  3. 纯Css3手工打造网页图片效果

    .rotate-demo { width: 220px; height: 220px; margin: 0 auto; background: no-repeat url("http://i ...

  4. ANE打包心得

    1 ane中的p12证书是fb或者flashide中生成的(例如air工程生成的p12),不是苹果账号的p12 2 打包bat中的 -platform 要和 extension.xml中的platfo ...

  5. python - 实现文本分类[简单使用第三方库完成]

    第三方库 pandas sklearn 数据集 来自于达观杯 训练:train.txt 测试:test.txt 概述 TF-IDF 模型提取特征值建立逻辑回归模型 代码 # _*_ coding:ut ...

  6. adb client, adb server, adbd原理浅析(附带我的操作过程)

    adb是什么? adb就是Android调试桥,很形象啊. 先来看adb原理的逻辑图: 再来进行实际操作:我的pc的ip是192.168.1.102, 我的android手机的ip为192.168.1 ...

  7. “全栈2019”Java第二十六章:流程控制语句中循环语句do-while

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  8. 使用concat做字符串拼接和数据迁移

    作用: 解决一开始数据库建立不合理造成的字段冗余,从而提取部分字段,数据迁移.拼接字符串的功能. 格式: concat(字段1,'间隔符',字段2....) concat_ws('间隔符',字段1,字 ...

  9. 【FAQ】maven包引入版本引发的问题

    pom.xml文件中的 dependency顺序可能会引起jar包版本不一致的问题,越上面越先引入进来

  10. python3之循环

    本节主要介绍python中循环语句的用法以及其他一些语句exec等,文章后面附有之前的文章: 循环语句 if是值执行一次而循环时在条件满足情况下可以执行相同语句多次:使用循环可以轻松实现序列,词典等的 ...