- Home /
Don't spawn if spawn point is in use
Hey,
I've had a look around but can't quite find the right stuff to put into this code, so I'd appreciate if someone could help me out.
I'm using the spawn script provided by Unity here: https://unity3d.com/learn/tutorials/projects/survival-shooter/more-enemies
I'm using the spawner to randomly spawn pickups around my map which do not move, however I want to be able to stop them from overlapping each other. Right now if I leave the code running I'll end up with an infinite number of pickups on each location. How would I amend this code to stop a new prefab from being instantiated in the same place as another?
Here is the function I'm using:
public class GemManager : MonoBehaviour {
public GameObject gem;
public float spawnTime = 3f;
public Transform[] spawnPoints;
public int spawnLimit = 10;
// Use this for initialization
void Start () {
InvokeRepeating("Spawn", spawnTime, spawnTime);
}
void Spawn()
{
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Instantiate(gem, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
Thanks for your help!
Answer by ShadyProductions · Mar 10, 2018 at 12:13 PM
Try this:
using System.Collections.Generic;
using UnityEngine;
public class GemManager : MonoBehaviour
{
public GameObject gem;
public float spawnTime = 3f;
public Transform[] spawnPoints;
public List<Transform> _usedSpawnPoints;
public int spawnLimit = 10;
// Use this for initialization
void Start()
{
_usedSpawnPoints = new List<Transform>();
InvokeRepeating("Spawn", spawnTime, spawnTime);
}
void Spawn()
{
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
if (!_usedSpawnPoints.Contains(spawnPoints[spawnPointIndex]))
{
Instantiate(gem, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
_usedSpawnPoints.Add(spawnPoints[spawnPointIndex]);
}
}
}
To allow a spawnpoint again just do _usedSpawnPoints.Remove(spawnPoints[spawnPointIndex]);
Thanks, got it working with your code! Just need to add in the _usedSpawnPoints.Remove now, but I've coded this game realllllly badly, so I need to rearrange a few things.