Unity协程(Coroutine)管理类——TaskManager工具分享

Babybus-u3d技术交流-Unity协程(Coroutine)管理类——TaskManager工具分享

尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com

在分享 vp_Timer
中提到,没有继承的MonoBehaviour,没有Update,InVoke 和StartCoroutine的机制,vp_Timer就是提供了InVoke的机制,而且还可以统一管理。本篇D.S.Qiu要分享的TaskManager就是一个协程 管理类。 TaskManager —— Unity3D Managed Coroutines with Start, Stop, Resume ,看着就觉得很强大,当然是对于我这种对协程理解不深的来说。下面贴出 The Motivation of the author:
/// 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.

代码很简单,但却很解渴,Unity官方只听过了StopCoroutine(string methodName)或StopAllCoroutine() 这两个停止方法,从api就会觉得Unity的整体方法论还不完善,所以才会觉得TaskManager的难能可贵。由于源码简单,就不做解释了,See source for document :
C#代码


/// 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);  
   }  
}  

/// 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);    }}
  Usage Example:

C#代码 


/// 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));
 

/// }
 

/// ----------------------------------------------------------------------------
 

/// 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));/// }/// ----------------------------------------------------------------------------

小结:
本文主要是分享我的收藏的一些“干货”,TaskManager 和 vp_Timer 在项目中发挥了很大的作用,D.S.Qiu 一再觉得强大的东西不都是复杂的,能够使用最简单的本质方法解决问题才是代码设计的追求。 文末附上了相关的链接以及TaskManager的代码。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容