我正在使用下面的Coroutine
在我的游戏列表中移动多个对象:
IEnumerator moveObjToRight (Transform fromPosition, Vector3 toPosition, float duration, int newIndex) {
while (freePositions.Contains(objPositions[newIndex])) {
freePositions.Add (objPositions [newIndex - 1]);
filledPositions.Remove (objPositions [newIndex - 1]);
float counter = 0;
Transform startTrans = fromPosition;
freePositions.Remove (objPositions [newIndex]);
filledPositions.Add (objPositions [newIndex]);
while (counter < duration) {
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp (startTrans.position, toPosition, counter / duration);
yield return null;
}
if (newIndex < objPositions.Count) {
newIndex++;
if ((newIndex == 9) || !freePositions.Contains (objPositions [newIndex])) {
isMovingLeft = true;
yield return new WaitForSeconds (2.0f);
if (freePositions.Contains (objPositions [newIndex - 2])) {
toPosition = new Vector3(objPositions[newIndex - 2], startTrans.position.y, startTrans.position.z );
yield return StartCoroutine(moveObjToLeft(startTrans, toPosition, 1.0f, newIndex - 2));
我用它按以下方式调用它:
StartCoroutine(moveObjToRight(objs [objs.Count - 1].getObjGameObject().transform, new Vector3(objPositions[indexInObjPositions + 1], objPositionY, camera.nearClipPlane), 1.0f, indexInObjPositions + 1));
我收到了以下错误:
MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Transform.get_position ()
在我的游戏中,指向协程中的行:
toPosition = new Vector3(objPositions[newIndex - 2], startTrans.position.y, startTrans.position.z );
我相信这是因为我在销毁游戏对象时没有停止协同程序。我怎样才能阻止上面的协程?
答案 0 :(得分:1)
您可以使用以下命令:
StopCoroutine(moveObjToRight);
在销毁对象之前,或者你可以使用布尔值作为标志来知道对象何时活着或被破坏,并控制协程是否运行。
bool alive = true;
Ienumerator moveobj{
if(alive){
//run code
}
}
Destroy(object);
alive = false;