- Home /
Random platform spawning with current code?
Hey Guys, I found a tutorial that shows you have to spawn platforms but the code during the tutorial wasn't explained properly. So what im trying to do is have a list of prefabs that spawns randomly based on condition for example if the score is above 300 then start spawning harder prefabs from the list, i just cant figure out how to do that with the current code. Any help would be appreciated.
using UnityEngine;
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++){
Recycle();
}
}
void Update () {
if(objectQueue.Peek().localPosition.x + recycleOffset < Player.distanceTraveled){
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;
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;
}
}
}
It doesn't look like the current code supports more than one prefab. I would modify it so that you have several prefabs at your disposal (reflecting easy, challenging, and difficult levels), and then weight the generator based on the player level. This will also likely require three objectQueues. Because this is the case, you might be better off with a spawn pool/manager. Although I haven't tried using it (only found it via a cursory Google search), you can try this pool manager.
Thanks for the reply, ill figure out how to get several prefabs in the pool, i did look at the pool manager before but ill try this first. thanks