Problem:
I’m trying to create a spawner that either instantiates a gameobject, and if not, will instantiate one item in its place.
For some reason it is sometimes spawning more than one item, or the gameobject and an item.
Question:
How can I adjust my code so that I’m not instantiating an item if a gameobject or item has already been created?
Current code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomPositionSpawner : MonoBehaviour
{
//public RoomCenter roomCenter;
private GameObject spawnPoint;
public GameObject[] spawnPoints;
public GameObject objectToSpawn;
private int spawnPointSelector;
public static bool spawnAllowed;
private GameObject tempGO;
public bool shouldSpawnItems;
public GameObject[] itemsToSpawn;
public int itemDropPercentChance;
private int randomItem;
// Use this for initialization
void Start()
{
Shuffle();
spawnAllowed = true;
SpawnObject();
}
public void Shuffle()
{
for (int i = 0; i < spawnPoints.Length; i++)
{
int rnd = Random.Range(0, spawnPoints.Length);
tempGO = spawnPoints[rnd];
spawnPoints[rnd] = spawnPoints[i];
spawnPoints[i] = tempGO;
}
}
void SpawnObject()
{
if (spawnAllowed)
{
Instantiate(objectToSpawn, spawnPoints[0].transform.position, Quaternion.identity);
if (shouldSpawnItems)
{
for (int i = 1; i < spawnPoints.Length; i++)
{
float dropChance = Random.Range(0f, 100f);
if (dropChance < itemDropPercentChance)
{
randomItem = Random.Range(0, itemsToSpawn.Length);
Instantiate(itemsToSpawn[randomItem], spawnPoints[i].transform.position, Quaternion.identity);
}
}
}
spawnAllowed = false;
}
}
}