他のスクリプトのコルーチンに対して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から呼び出していました。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed;
//goalの位置までスムーズに移動する
public IEnumerator MoveTo( Vector3 goal) {
while (Vector3.Distance(transform.position, goal) > 0.05f)
{
Vector3 nextPos = Vector3.Lerp(transform.position, goal, Time.deltaTime * speed);
transform.position = nextPos;
yield return null;//ここまでが1フレームの間に処理される
}
transform.position = goal;
print("終了");
yield break;//処理が終わったら破棄する
}
}
using UnityEngine;
public class KickBall : MonoBehaviour
{
public Transform target;
private Vector3 targetPos;
private Coroutine myCor;
// Start is called before the first frame update
void Start()
{
targetPos = target.position;
}
private void OnTriggerEnter(Collider other)
{
//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()を外から呼び出すことでエラーメッセージを吐いてしまうのかも、と思い、下記のように変更してメッセージが出ないようにしました。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed;
private Coroutine myCor;
//MoveToをスタートさせるメソッド
//外部からコルーチンを呼び出すときはこのメソッドを使う
public void StartCor(Vector3 goal)
{
if (myCor != null)
{
StopCoroutine(myCor);//StartCoroutine()する前に停止させて、重複して実行されないようにする。
}
myCor = StartCoroutine(MoveTo(goal));
}
//goalの位置までスムーズに移動する
public IEnumerator MoveTo( Vector3 goal) {
while (Vector3.Distance(transform.position, goal) > 0.05f)
{
Vector3 nextPos = Vector3.Lerp(transform.position, goal, Time.deltaTime * speed);
transform.position = nextPos;
yield return null;//ここまでが1フレームの間に処理される
}
transform.position = goal;
print("終了");
yield break;//処理が終わったら破棄する
}
}
using UnityEngine;
public class KickBall : MonoBehaviour
{
public Transform target;
private Vector3 targetPos;
private Coroutine myCor;
// Start is called before the first frame update
void Start()
{
targetPos = target.position;
}
private void OnTriggerEnter(Collider other)
{
//StartCor()を使ってMove.csのMoveToを開始
other.GetComponent<Move>().StartCor(targetPos);
}
}