- Home /
Trigger...Spawn...Destroy
Hi everyone, Im running into a little problem. As soon as I hit a trigger I want an enemy to spawn. I only want one enemy on the field. Now when I hit the trigger again I want that enemy that is on the field to destroy it self while the next enemy is about to spawn. Any ideas on how to do so? Do I use a "Destroy" Assignment on this? Heres what I have:
public GameObject Enemy;
public float mytimer;
void Start()
{
GameObject player = GameObject.Find("Player");
}
void spawnEnemy() {
Transform enemy;
GameObject enemySpawnPoint = GameObject.Find("EnemySpawn");
enemy = Instantiate(Enemy,enemySpawnPoint.transform.position,enemySpawnPo int.transform.rotation) as Transform;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "EnemyTrigger") {
mytimer = Random.Range(0,10);
Invoke("spawnEnemy", mytimer);
Debug.Log("Spawn Normal");
}
}
}
Answer by dorpeleg · Oct 28, 2014 at 02:36 PM
You got some of it down.
Here is a script that should do what you asked:
public GameObject Enemy; // the enemy prefab
public float MyTimer; // the time to wait before spawn
private GameObject _spawndEnemy; // the enemy that was spawnd
void SpawnEnemy()
{
var enemySpawnPoint = GameObject.Find("EnemySpawn").transform;
_spawndEnemy = Instantiate(Enemy, enemySpawnPoint.position, enemySpawnPoint.rotation) as GameObject;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "EnemyTrigger") {
mytimer = Random.Range(0,10);
Destroy(_spawndEnemy);
Invoke("SpawnEnemy", mytimer);
Debug.Log("Spawn Normal");
}
}
Your answer
Follow this Question
Related Questions
Respawn destroyed object 1 Answer
How do I detect if there's an object at the same position and destroy ONLY ONE of them? 1 Answer
Spawning objects on trigger does not work as expected 2 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Target touching enemy collision 1 Answer