So I want to be able to know if a game object is destroyed from an array and the array count will be for example is 5, when a game object is destroyed, the count will be then be reduced to four. And if the count is less than 5, I want to be able to instantiate another game object.
This is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnEnemy : MonoBehaviour {
public GameObject[] go;
public Vector3 spawnPosition;
public int spawnLimit;
public int spawnCount;
public bool spawn;
public float waitTime;
public float timer;
void Start(){
}
void Update(){
if(spawn){
timer += Time.deltaTime;
if (timer > waitTime) {
if (spawnCount < spawnLimit) {
Spawn ();
timer = 0.0f;
} else {
spawn = false;
Debug.Log ("Spawn limit has been reached!");
}
}
}
}
void Spawn(){
GameObject gos = go [Random.Range(0, go.Length)];
Instantiate (gos, spawnPosition, Quaternion.Euler (90, 0, 0));
spawnCount++;
Debug.Log ("Spawned game object #" + spawnCount);
}
}
You could create another script assignable to the spawned object that notifies SpawnEnemy when it’s destroyed (or just handle it inside your enemy AI script when it dies/is destroyed).
Here would be your SpawnEnemy:
using UnityEngine;
public class SpawnEnemy : MonoBehaviour
{
public GameObject[] go;
public Vector3 spawnPosition;
public int spawnLimit;
public float waitTime;
bool spawn;
float timer;
int spawnCount;
void Update()
{
if (spawn)
{
timer += Time.deltaTime;
if (timer > waitTime)
{
if (spawnCount < spawnLimit)
{
Spawn();
timer = 0.0f;
}
else
{
spawn = false;
Debug.Log("Spawn limit has been reached!");
}
}
}
}
void Spawn()
{
GameObject gos = go[Random.Range(0, go.Length)];
GameObject spawned = Instantiate(gos, spawnPosition, Quaternion.Euler(90, 0, 0));
spawnCount++;
SpawnedObject spawnedObject = spawned.AddComponent<SpawnedObject>();
spawnedObject.spawner = this;
Debug.Log("Spawned game object #" + spawnCount);
}
public void Despawn()
{
spawnCount--;
spawn = true;
}
}
and here is a sample script to notify SpawnEnemy:
using UnityEngine;
public class SpawnedObject : MonoBehaviour
{
public SpawnEnemy spawner;
void OnDestroy()
{
if (spawner != null)
spawner.Despawn();
}
}