I have a camera following the player. Once the player reaches a specific point I instantiate a prefab just off screen. When that prefab passes through the scene, I recycle it and put it back to the front of the scene. Now I want to add a random range to the y axis, which works fine, except it only moves down, and it keeps moving down.
I have been staring at my script for hours and I just cant figure it out. Here’s my code. Please excuse the organization, I know it’s atrocious.
using UnityEngine;
using System.Collections.Generic;
public class CollectibleScript : MonoBehaviour {
public Transform prefab;
public int numberOfObjects;
public float recycleOffset;
public Vector3 startPosition;
public GameObject camera;
private float x, y, z;
private float resetX;
private float resetY;
private Vector3 nextPosition;
private Queue<Transform> objectQueue;
void Start () {
x = PlayerController.distanceTraveled + 14f;
y = camera.transform.position.y;
z = -35f;
resetX = PlayerController.distanceTraveled + 30f;
resetY = y + Random.RandomRange (-7.5f, 5f);
objectQueue = new Queue<Transform>(numberOfObjects);
nextPosition = startPosition;
for (int i = 0; i < numberOfObjects; i++) {
Transform o = (Transform)Instantiate(prefab);
o.localPosition = nextPosition;
objectQueue.Enqueue(o);
}
}
void Update () {
startPosition = new Vector3 (x, resetY, z);
if (objectQueue.Peek().localPosition.x + recycleOffset < PlayerController.distanceTraveled) {
Transform o = objectQueue.Dequeue();
o.localPosition = nextPosition;
nextPosition.x += resetX;
nextPosition.y += resetY;
objectQueue.Enqueue(o);
}
}
}