封装你的协程Unity TaskManager
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的更多相关文章
- 聊一聊Unity协程背后的实现原理
Unity开发不可避免的要用到协程(Coroutine),协程同步代码做异步任务的特性使程序员摆脱了曾经异步操作加回调的编码方式,使代码逻辑更加连贯易读.然而在惊讶于协程的好用与神奇的同时,因为不清楚 ...
- python学习笔记-(十四)进程&协程
一. 进程 1. 多进程multiprocessing multiprocessing包是Python中的多进程管理包,是一个跨平台版本的多进程模块.与threading.Thread类似,它可以利用 ...
- Python开发【第九章】:线程、进程和协程
一.线程 线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务 1.t ...
- Python 协程了解
协程: 1.协程,又称微线程,纤程.英文名Coroutine. 2.协程是跑在线程内的单线程,串行没有锁. 3.协程是一种用户态的轻量级线程. 4.协程CPU是访问不到的,协程是用户自己控制的. ...
- Python全栈开发-Day10-进程/协程/异步IO/IO多路复用
本节内容 多进程multiprocessing 进程间的通讯 协程 论事件驱动与异步IO Select\Poll\Epoll——IO多路复用 1.多进程multiprocessing Python ...
- C高级 跨平台协程库
1.0 协程库引言 协程对于上层语言还是比较常见的. 例如C# 中 yield retrun, lua 中 coroutine.yield 等来构建同步并发的程序. 本文就是探讨如何从底层实现开发级别 ...
- Python学习笔记整理总结【网络编程】【线程/进程/协程/IO多路模型/select/poll/epoll/selector】
一.socket(单链接) 1.socket:应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socke ...
- python-进程、线程与协程
基础概念 进程 是一个执行中的程序,即将程序装载到内存中,系统为它分配资源的这一过程.进程是操作系统资源分配的基本单位. 每一个进程都有它自己的地址空间,一般情况下,包括文本区域(text regio ...
- 协程分析之context上下文切换
协程现在已经不是个新东西了,很多语言都提供了原生支持,也有很多开源的库也提供了协程支持. 最近为了要给tbox增加协程,特地研究了下各大开源协程库的实现,例如:libtask, libmill, bo ...
随机推荐
- 查看SSD寿命
查看SSD寿命 起初买mac book pro的时候挺担心SSD使用寿命的,过保了后,还搞了个移动硬盘,尽可能的把编译什么的都移动到移动硬盘上进行,实际上这样做都是没有必要的. 安装软件smartct ...
- C# 数字转换成汉字大写 数值转换成汉字大写
1.数字转换成汉字大写 public string NumToChinese(string x) { //数字转换为中文后的数组 //转载请注明来自 http://www.shang11.com st ...
- Linux下开放指定端口
今天Linux测试服务器重启了下 结果导致网站打不开了,ip也能ping通 Apache重启成功,telnet了下80端口结果连不上,这就应该是外网80被防火墙拦截了 后面把80端口开发了下可以了,步 ...
- WinForm中的重绘 - 按钮等控件的背景渐变色重绘
注:brush通过起止坐标来控制重绘范围及方向.比如从上到下渐变时,brush第二个Point参数是左下角坐标. private void PaintGradientBackground(Button ...
- Python【流程控制与循环】
本文介绍 1.流程控制 2.while循环 一.流程控制 单分支 if 条件: ...Python代码,满足条件执行 双分支 if 条件: ...Python代码,满足条件执行 else: ...Py ...
- JavaScript类型检测汇总
曾经我以为JavaScript中的类型检测只要使用 typeof 或 instanceof 就可以通通解决.后来我发现我是too young too naive啊!早说过JavaScript是 ...
- 编写高质量JS代码上
想写出高效的javascript类库却无从下手: 尝试阅读别人的类库,却理解得似懂给懂: 打算好好钻研js高级函数,但权威书上的内容太零散, 即使记住“用法”,但到要“用”的时候却没有想“法”. 也许 ...
- 爬虫开发10.scrapy框架之日志等级和请求传参
今日概要 日志等级 请求传参 今日详情 一.Scrapy的日志等级 - 在使用scrapy crawl spiderFileName运行程序时,在终端里打印输出的就是scrapy的日志信息. - 日志 ...
- BAT机器学习面试1000题系列(41-45题)
41.线性分类器与非线性分类器的区别以及优劣 如果模型是参数的线性函数,并且存在线性分类面,那么就是线性分类器,否则不是.常见的线性分类器有:LR,贝叶斯分类,单层感知机.线性回归常见的非线性分类器: ...
- 读取xml文件内容到数据库
前言 前言不搭后语·················· 内容 听某个大牛说他们的公司常常会涉及到从xml文件中读数据到写入到数据库,序列化的时候会遇到这这个问题,将要持久化的数据到xml文件存储起来, ...