情境:我指的是我的项目中的tutorial,代码中有一个对象池概念。
问题:在我编写生成平台(platformmanager.cs)的脚本之后,会出现一个异常,说,
InvalidOperationException:由于当前
对象的状态
system.collections.generic.queue`1[unityengine.transform].peek()
platformmanager.update()(位于assets/platform/platformmanager.cs:35)
platformmanager.cs脚本:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlatformManager  : MonoBehaviour {
    public Transform prefab;
    public int numberOfObjects;
    public float recycleOffset;
    public Vector3 startPosition;
    public Vector3 minSize, maxSize,minGap, maxGap;
    public float minY, maxY;
    private Vector3 nextPosition;
    private Queue<Transform> objectQueue;

    void Start () {
        objectQueue = new Queue<Transform>(numberOfObjects);
        for (int i = 0; i < numberOfObjects; i++) {
            objectQueue.Enqueue((Transform)Instantiate(prefab));
        }
        nextPosition = startPosition;
        for (int i = 0; i < numberOfObjects; i++) {
            Transform o = (Transform)Instantiate(prefab);
            o.localPosition = nextPosition;
            nextPosition.x += o.localScale.x;
            objectQueue.Enqueue(o);
        }
    }

    void Update () {
        if (objectQueue.Peek().localPosition.x + recycleOffset < Runner.distanceTraveled)//THIS IS THE 35TH LINE WHICH CAUSE THE ERROR
     {
            Transform o = objectQueue.Dequeue();
            o.localPosition = nextPosition;
            nextPosition.x += o.localScale.x;
            objectQueue.Enqueue(o);
            Recycle();
        }
    }

    private void Recycle () {
    Vector3 scale = new Vector3(
            Random.Range(minSize.x, maxSize.x),
            Random.Range(minSize.y, maxSize.y),
            Random.Range(minSize.z, maxSize.z));

        Vector3 position = nextPosition;
        position.x += scale.x * 0.5f;
        position.y += scale.y * 0.5f;

        Transform o = objectQueue.Dequeue();
        o.localScale = scale;
        o.localPosition = position;
        nextPosition.x += scale.x;
        objectQueue.Enqueue(o);

        nextPosition += new Vector3(
            Random.Range(minGap.x, maxGap.x) + scale.x,
            Random.Range(minGap.y, maxGap.y),
            Random.Range(minGap.z, maxGap.z));

        if(nextPosition.y < minY){
            nextPosition.y = minY + maxGap.y;
        }
        else if(nextPosition.y > maxY){
            nextPosition.y = maxY - maxGap.y;
        }
    }
}

提前谢谢。

最佳答案

确保队列不为空。

if(objectQueue.Count != 0)
{
     if (objectQueue.Peek().localPosition.x + recycleOffset < Runner.distanceTraveled)//THIS IS THE 35TH LINE WHICH CAUSE THE ERROR
     {
            Transform o = objectQueue.Dequeue();
            o.localPosition = nextPosition;
            nextPosition.x += o.localScale.x;
            objectQueue.Enqueue(o);
            Recycle();
        }
}

10-04 10:38