- Home /
How can I spawn another game object once one has been destroyed?
I am currently using this script to spawn a limit of two game objects.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class newSpawn : MonoBehaviour {
public Transform[] spawnPoints;
public GameObject enemy;
public int enemyCount = 0;
public int enemyLimit = 2;
void Start () {
startInvoke ();
}
void startInvoke()
{
InvokeRepeating ("spawn", 0f, 5f);
}
void spawn()
{
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
if(enemyCount >= enemyLimit) return;
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
enemyCount++;
}
}
How would I then tell the script to spawn another game object once one is destroyed, keeping the total at 2?
Any help much apprecated.
Answer by RetroGeek46 · Mar 13, 2018 at 07:51 PM
You can use the Update function to keep track of when an object is destroyed, and when that happens you can call the spawn function again.
I don't see you destroying the object in this script, but wherever that is happening, update the enemyCount variable over there (maybe declare it static if object is destroyed in a different script), and then use Update function to spawn a new one. It will look somewhat like this
...
Destroy(gameObject);
enemyCount--;
...
And then in current script you introduce a new function
void Update() {
if(enemyCount < enemyLimit)
spawn();
}
I think if you use the Update function, you might not need to use InvokeRepeating(), but that completely depends on what you are trying to achieve.
Thanks! That makes sense. However, I am having some issues getting the enemyCount variable over into the destroy game object script. How would I do that?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class kill$$anonymous$$e : $$anonymous$$onoBehaviour {
void OnCollisionEnter (Collision col)
{
if (col.gameObject.name == "saber")
{
$$anonymous$$illEnemy();
}
}
void $$anonymous$$illEnemy()
{
Destroy(this.gameObject);
}
}
Thanks for your help!
In your newSpawn script, declare the enemyCount variable as static
public static int enemyCount;
Then in the kill$$anonymous$$e script, use it with
Destroy(this.gameObject);
newSpawn.enemyCount--;
Answer by IronManBK · Mar 14, 2018 at 12:51 PM
You create 2 object, and hide them, then you just have to unhide each of them by their index and time they exist appropiately.