- Home /
Respawning Single Enemy at a Random Range
Hi there,
I am quite confused at the moment, just can't seem to wrap my head around this issue. It is a game 1v1 where the player has to kill the enemy as many times as they can in an allocated time frame. The issue I am facing is how can I respawn that enemy once they are killed. With my script, it works great for the first one but after the first one, it doesn't work anymore. I Know the issue is Destroy(gameObject, 1f) but I am unaware of how to remove the enemy from the screen and spawn it back. The code is below
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
public int scoreValue = 100;
public GameObject enemyPrefab;
bool isDead;
void Start ()
{
}
void Update ()
{
if (isDead == true)
{
Vector3 position = new Vector3(35f, Random.Range(-34.0f, 71.0f), 118f);
Instantiate(enemyPrefab, position, Quaternion.identity);
isDead = false;
}
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Bullet")
{
print("Hit bullet");
Destroy(other.gameObject);
Death();
Destroy(gameObject, 1f);
}
}
void Death()
{
isDead = true;
Game_Manager.score += scoreValue;
}
}
Answer by Kossuranta · Nov 28, 2016 at 01:43 PM
First of all you got this a little bit wrong. Currently the enemy isn't respawnin, but the script will spawn new enemy when it dies, but when it spawns the new enemy it probably doesn't have "enemyPrefab" assigned and cannot spawn new enemy. You could assign enemyPrefab at the "Assets" folder or in it's sub folder where you have prefabs and not in scene.
Or to make it "respawn" don't destroy it at all, just change its position instead of Instantiating new enemy.
But what I think you should do, is totally different script that will handle spawning while this one handles enemies death. With own script you could have it working like it does now by calling public method from that script that will spawn new enemy or you could have certain amount of enemies at the same time. Check how many enemies there are on the scene, if not enough spawn more.
When I re-read the code, I could see the issue but couldn't quite fit what was actually going wrong. The first theory I have already tried setting the prefab in the actual prefab so when it spawns it would be the enemy.
So when death animation plays out just relocate it to a new position. interesting. I will try that method and see how it flows.
The main mechanic of the game is to be a 1v1 so spawning more enemies really isn't in the books yet. But I feel like two scripts to handle different things might make a little more sense to have some flow in the game.
Your answer
Follow this Question
Related Questions
Enemy Spawner help 1 Answer
How to spawn gameobject from host to all clients 1 Answer
Spawn OnTriggerEnter 0 Answers
Make enemy spawn only if the previous one spawned it out of the way. 0 Answers