Coroutine原来是这样用的 【 Unity3D教程】

unity3d开发中Coroutine到底是怎么用的?

昨天在测试的时候发生了很严重的当机事件,不管用什么Android的手机,在游玩过程中会不定时的无任何警示讯息自动跳出,从LogCat看讯息发现:

1.ERROR/InputDispatcher(284): channel '418b6698 path.to.our.app (server)' ~ Consumer closed input channel or an error occurred.  events=0×8

2.ERROR/InputDispatcher(284): channel '418b6698 path.to.our.app (server)' ~ Channel is unrecoverably broken and will be disposed!

这时先冷静想想这几天加了什么东西?灵机一动,会不会是State Machine用Coroutine执行出了问题呢?来看看State在实做上的写法:

internal abstract class XAIState {

  protected XAIController _m_ai = null;

  public XAIController ai { get { return _m_ai; } }

  public virtual void Enter ( XAIController ai ) {}

  public virtual IEnumerator Execute () { yield return null; }

  public virtual void Exit () {}

  }

  internal class XAIWaitState : XAIState {

  public override void Enter ( XAIController ai ) {

  _m_ai = ai;

  ai.StartCoroutine( Execute() );

  }

  public IEnumerator void Execute () {

  while( ture ) {

  //Do somthing... for Waiting!!

  yield return null;

  }

  }

  public override void Exit () {

  ai.StopAllCoroutine( );

  }

  }

  internal class XAIRunState : XAIState {

  public override void Enter ( XAIController ai ) {

  _m_ai = ai;

  ai.StartCoroutine( Execute() );

  }

  public IEnumerator void Execute () {

  while( ture ) {

  //Do somthing... for Run

  yield return null;

  }

  }

  public override void Exit () {

  ai.StopAllCoroutine( );

  }

  }

  public class XAIController : MonoBehaviour {

  private XAIState _m_currentState = null;

  internal XAIWaitState _m_waitState = new XAIWaitState();

  internal XAIRunState _m_runState = new XAIRunState();

       //unity3d http://www.unitymanual.com/5439.html

  protected void Start () {

  SwitchState( _m_waitState );

  }

  private void SwitchState ( XAIState state ) {

  if( _m_currentState != null )

  _m_currentState.Exit();

  _m_currentState  = state;

  if( _m_currentState != null )

  _m_currentState.Enter();

  }

  }


从上面看来原码在Compile上没错、也没有WARNING,不会有问题吧!殊不知,State在执行期间频繁的切换Start、Stop Coroutine的动作会让Andorid在不定时的状态下Crash,而且完全没有任何警讯!


结论:

如果你也有遇到相同的问题,请想想有没有甚麽地方跟我一样,在Class之间彼此不断的Start、Stop Coroutine,如果有!那可能就是Crash的关键。

至于我怎么解掉这个问题的呢?方法很烂,我想大家因该都知道了,就是用void Update()来解决,不要自以为用Coroutine很屌。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值