Hi there. I’m new to Unity/C# and I have tried my best to follow online tutorials. Doing exactly what someone describes is easy enough, but I think of things I would like to do differently to make the game more fun for me. I created a simple game that has a ball rolling down a long narrow plane. I placed rectangles as obstacles that move between certain X values forever so that when the ball hits the obstacles the movement stops and the level starts over. Placing each piece is time-consuming, and I wanted to see if I could figure out how to automatically generate the obstacles on the plane between certain X and Z ranges. I looked at several “spawner” tutorials and the code below is the closest that I could get.
Sometimes, however, the rectangles spawn at the same or nearly the same location, crash into each other and fly off the plane or start moving in the wrong direction. I can’t seem to find a way to have the obstacles spawn randomly, but make sure that one obstacle is a minimum distance from another obstacle.
Thank you for any and all assistance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public int numberToSpawn;
public List<GameObject> spawnPool;
public GameObject quad;
void Start()
{
spawnObjects();
}
public void spawnObjects()
{
destroyObjects();
int randomItem = 0;
GameObject toSpawn;
MeshCollider c = quad.GetComponent<MeshCollider>();
float screenX,screenY, screenZ;
// Vector3 pos;
for (int i = 0; i < numberToSpawn; i++)
{
randomItem = Random.Range(0, spawnPool.Count);
toSpawn = spawnPool[randomItem];
screenX = Random.Range(-6f, 6f);
screenY = transform.position.y;
screenZ = Random.Range(20f, 800f);
// pos = new Vector3(screenX, screenY, screenZ);
Instantiate(toSpawn, new Vector3(screenX, screenY, screenZ), toSpawn.transform.rotation);
}
}
private void destroyObjects()
{
foreach (GameObject o in GameObject.FindGameObjectsWithTag("Obstacle"))
{
Destroy(o);
}
}
}