取消异步操作

Its definitely frustrating theres no StopCoroutine that takes a Coroutine. I rarely ever start them with a string to begin with.

So one way you could accomplish this is by using something like this:

Code:  
  1. class CancellingCoroutine : IEnumerator
  2. {
  3.     public bool stop;
  4.  
  5.     IEnumerator enumerator;
  6.     MonoBehaviour behaviour;
  7.  
  8.     public readonly Coroutine coroutine;
  9.  
  10.     public CoroutineStopable ( MonoBehaviour behaviour, IEnumerator enumerator )
  11.     {
  12.         this. behaviour = behaviour;
  13.         this. enumerator = enumerator;
  14.         this. coroutine = behaviour. StartCoroutine ( this );
  15.     }
  16.  
  17.     public object Current { get { return enumerator. Current; } }
  18.     public bool MoveNext { return !stop && enumerator. MoveNext ( ); }
  19.     public void Reset ( ) { enumerator. Reset ( ); }
  20.     public void Dispose ( ) { enumerator. Dispose ( ); }
  21.     public implicit operator YieldStatement ( CancellingCoroutine self ) { return self == null ? null : self. coroutine; }
  22. }


Then to start it you would do:

Code:  
  1. CancellingCoroutine ccoroutine = new CancellingCoroutine ( this, CoFunctionEnumerator ( ) );

To wait for it

Code:  
  1. yield return ccoroutine. coroutine;

Then to stop it

Code:  
  1. ccoroutine. stop = true;


Its a hacky work around and it would be alot better if YieldStatement wasnt functionally sealed.


If you change your IEnumerator functions to use IEnumerator<YieldStatement> instead it'd be best. But i don't know how that would fair for builtin stuff like Start...

You could also set a done variable in the class when MoveNext returns false, thus allowing you to wait multiple times.

转载unity3d论坛:http://forum.unity3d.com/threads/102817-Coroutine-Control-and-StartCoroutine()-Coroutine

转载于:https://www.cnblogs.com/newyue/p/3485644.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值