封装你的协程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 ...
随机推荐
- delphi数组之菜鸟篇
数组是可以通过索引来引用的同类型数据的列表.按照存储空间的获取方式,Delphi支持的数组类型有两种,即静态数组和动态数组.所谓静态数组就是在声明时就已经确定大小的数组类型,而动态数组是指其大小在声明 ...
- Android-广播发送与接收(Java代码中订阅)
Android四大组件之一广播,使用的也比较多,广播可大致分为两种,一种是Android系统区域的广播,是由系统指令发出,例如:点亮屏幕广播,开机过程中的一些广播 省略…, 然而还有一种广播就是我们自 ...
- php的数组汉字符串常用函数
<?php// function add($a,$b,$func){// if(!is_callable($func)){// return false;// }// $m=$a+$b+$fun ...
- [CSS]利用伪元素实现一些特殊图形 from baidu校招
最近在博客园看到某人发的baidu校招题目,说是要用一行html代码实现下面的这个图形: 给定的html代码是: <div class='square'></div> ---- ...
- redis详细说明
# By default Redis does not run as a daemon. Use 'yes' if you need it.# Note that Redis will write a ...
- day03.2-内置函数的使用
1. 取绝对值函数,abs() res = abs(-1) print(res) """ 运行结果:1 结果分析:计算-1的绝对值 """ ...
- 迫不得已! ! 仅仅针对IE浏览器的样式,尤其是IE8及以下
IE10不会起作用,IE9,8,7,6,5都可以 <html> <head> <title>IE打开就是蓝色背景,白色的字体</title> <! ...
- Metasploit Penetration Testing
1.Metasploit整体框架: Shell中直接输入msfconsole启动PostgreSQL数据库服务 :service postgresql start 监听5432端口初始化Metaspl ...
- [ActionScript 3.0] 自定义右键菜单
将自定义右键菜单的一些属性和方法归纳到AddRightMenu.as,通过实例化此类,调用相关方法即可测试! package { import flash.display.Sprite; import ...
- node.js的总结-可以应付bat的社招面试
什么是NodeJS Node.js采用模块化结构,按照CommonJS规范定义和使用模块.模块与文件是一一对应关系,即加载一个模块,实际上就是加载对应的一个模块文件. JS是脚本语言,脚本语言都需要一 ...