- Home /
3D infinite runner game platform generation gives an error
Situation: I am referring to http://catlikecoding.com/unity/tutorials/runner/ tutorial for my project,and there is an object pooling concept within the code
Problem: What happens is , after i scripting the generation platform(PlatformManager.cs), i get an exceptions saying,
InvalidOperationException: Operation is not valid due to the current state of the object System.Collections.Generic.Queue`1[UnityEngine.Transform].Peek () PlatformManager.Update () (at Assets/Platform/PlatformManager.cs:35)
PlatformManager.cs script:
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 () {
//FOLLOWING LINE IS THE 35TH LINE
if (objectQueue.Peek().localPosition.x + recycleOffset < Runner.distanceTraveled) {
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;
}
}
}
Your answer
Follow this Question
Related Questions
Can anyone help me with my 2D endless runner overlapping platforms? 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Endless Runner Overlapping Platforms Bug 0 Answers
4 C# errors Endless Runner 0 Answers