他のスクリプトのコルーチンに対してStopCoroutine()しようとすると、エラーが吐き出されました。
でも実行はされるので、問題はないけどエラーメッセージが邪魔...。
他のスクリプトから直接StopCoroutine()するのではなく、StopCoroutine()させるメソッドを作って間接的に実行させました。
【環境】
・Mac OSX El Capitan
・Unity versiton:2018.3.0
【実行状況】
BallオブジェクトがStartオブジェクトとGoalオブジェクトの間を行き来するプログラムです。
BallオブジェクトにはMove.cs、StartとGoalオブジェクトにはKickBall.csをアタッチしています。
Move.csのIEnumerator MoveTo( Vector3 goal)をKickBall.csから呼び出していました。
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassMove:MonoBehaviour{publicfloatspeed;//goalの位置までスムーズに移動するpublicIEnumeratorMoveTo(Vector3goal){while(Vector3.Distance(transform.position,goal)>0.05f){Vector3nextPos=Vector3.Lerp(transform.position,goal,Time.deltaTime*speed);transform.position=nextPos;yieldreturnnull;//ここまでが1フレームの間に処理される}transform.position=goal;print("終了");yieldbreak;//処理が終わったら破棄する}}
usingUnityEngine;publicclassKickBall:MonoBehaviour{publicTransformtarget;privateVector3targetPos;privateCoroutinemyCor;// Start is called before the first frame updatevoidStart(){targetPos=target.position;}privatevoidOnTriggerEnter(Colliderother){//Move.csのコルーチンを止めようとするとエラーメッセージが出たif(other.GetComponent<Move>().myCor!=null){StopCoroutine(other.GetComponent<Move>().myCor);}other.GetComponent<Move>().myCor=StartCoroutine(other.GetComponent<Move>().MoveTo(targetPos));}}
【解決方法】
下記フォーラムによると、
https://answers.unity.com/questions/989547/coroutine-continue-failure-when-using-stopcoroutin.html
Make sure to call StopCoroutine() on the same object (MonoBehavior) that you started the coroutine.
コルーチンをスタートさせたオブジェクト(MonoBehavior)と同じオブジェクト内でStopCoroutine()を呼び出していることを確かめてください。
とあります。
同じMonoBehaviorでStartCoroutine()してるんですが、StopCoroutine()を外から呼び出すことでエラーメッセージを吐いてしまうのかも、と思い、下記のように変更してメッセージが出ないようにしました。
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassMove:MonoBehaviour{publicfloatspeed;privateCoroutinemyCor;//MoveToをスタートさせるメソッド//外部からコルーチンを呼び出すときはこのメソッドを使うpublicvoidStartCor(Vector3goal){if(myCor!=null){StopCoroutine(myCor);//StartCoroutine()する前に停止させて、重複して実行されないようにする。}myCor=StartCoroutine(MoveTo(goal));}//goalの位置までスムーズに移動するpublicIEnumeratorMoveTo(Vector3goal){while(Vector3.Distance(transform.position,goal)>0.05f){Vector3nextPos=Vector3.Lerp(transform.position,goal,Time.deltaTime*speed);transform.position=nextPos;yieldreturnnull;//ここまでが1フレームの間に処理される}transform.position=goal;print("終了");yieldbreak;//処理が終わったら破棄する}}
usingUnityEngine;publicclassKickBall:MonoBehaviour{publicTransformtarget;privateVector3targetPos;privateCoroutinemyCor;// Start is called before the first frame updatevoidStart(){targetPos=target.position;}privatevoidOnTriggerEnter(Colliderother){//StartCor()を使ってMove.csのMoveToを開始other.GetComponent<Move>().StartCor(targetPos);}}