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在实做上的写法:
从上面看来原码在Compile上没错、也没有WARNING,不会有问题吧!殊不知,State在执行期间频繁的切换Start、Stop Coroutine的动作会让Andorid在不定时的状态下Crash,而且完全没有任何警讯!
结论:
如果你也有遇到相同的问题,请想想有没有甚麽地方跟我一样,在Class之间彼此不断的Start、Stop Coroutine,如果有!那可能就是Crash的关键。
至于我怎么解掉这个问题的呢?方法很烂,我想大家因该都知道了,就是用void Update()来解决,不要自以为用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很屌。