Hello Unity folks,
I have customized a script for my game but I have a couple of questions about it.
The script I have is choosing the prefab (I have several but the script won’t allow me to add more than 1 in the inspector) and is stacking that prefab on itself to end up with an endless game. The game exists of obstacles that the main character has to dodge. This script recognizes the distance the player has traveled and is spawning and deleting the prefabs out of view.
I would like to adjust that script so u can drag more prefabs into the inspector.
I would like to adjust the script so it would choose the prefabs randomly.
the inspector looks like this:
The script I have is:
using UnityEngine;
using System.Collections.Generic;
public class LevelManager : MonoBehaviour {
public Transform prefab;
public int numberOfObjects;
public float recycleOffset;
public Vector3 startPosition;
public Vector3 minSize, maxSize, minGap, maxGap;
public float minX, maxX;
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++){
Recycle();
}
}
void Update () {
if(objectQueue.Peek().localPosition.y + recycleOffset < PlayerMovement.distanceTraveled - 15f){
Recycle();
}
}
private void Recycle () {
Vector3 scale = new Vector3(
Random.Range(minSize.y, maxSize.y),
Random.Range(minSize.x, maxSize.x),
Random.Range(minSize.z, maxSize.z));
Vector3 position = nextPosition;
position.y += scale.y * 1f;
position.x += scale.x * 1f;
Transform o = objectQueue.Dequeue();
o.localScale = scale;
o.localPosition = position;
objectQueue.Enqueue(o);
nextPosition += new Vector3(
Random.Range(minGap.y, maxGap.y) + scale.y,
Random.Range(minGap.x, maxGap.x),
Random.Range(minGap.x, maxGap.x));
if(nextPosition.x < minX){
nextPosition.x = minX + maxGap.x;
}
else if(nextPosition.x > maxX){
nextPosition.x = maxX - maxGap.x;
}
}
}
The original script was spawning cubes which were also randomly adjusted by size. I managed to turn this off, but that is the reason it is still in the script. If somebody knows how to remove this it would be better and more efficient, but it is not priority
Thank you in advance