- Home /
[C#] Respawning system Enemies
I am making a game where once you kill an enemy, two more respawn and you score is based off of that. So far it was working for the first 2. I killed the first enemy, so it spawned two more but once i killed those, the 4 enemies that respawned were frozen in place but still had all the scripts on it, Idk if its a problem with my code so here it is:
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour
{
public int maxHealth;
public int curHealth;
protected Animation dmg;
public Rigidbody2D enemyPrefab;
void Start()
{
dmg = GetComponent<Animation>();
curHealth = maxHealth;
}
void Update()
{
if (curHealth < 1)
{
Death();
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Bullet")
{
curHealth -= 1;
Destroy(col.gameObject);
dmg.Play("Damage");
}
}
void Death()
{
Destroy(gameObject);
Rigidbody2D aPrefab = Instantiate(enemyPrefab, new Vector3(0, 0, 0), transform.rotation) as Rigidbody2D;
Rigidbody2D bPrefab = Instantiate(enemyPrefab, new Vector3(0, 0, 0), transform.rotation) as Rigidbody2D;
}
}
Thanks
A wild guess would be that they might just spawn too low and end up getting stuck in the ground.
Also a small suggestion would be to , perhaps, not use Destroy(...), but create a object pool for the enemies and re-use them if you will end up creating more and more enemies rather than create/destroy the objects all the time. http://gameprogram$$anonymous$$gpatterns.com/object-pool.html
why don't use player script for spawning because i don't know if it's ok that enemy destroy them self's & instantiate others. & lastly use public GameObject enemyPrefab;
ins$$anonymous$$d of public Rigidbody2D enemyPrefab;
I had a similar problem once and it was caused by the source game object that was instantiated being destroyed. In order to fix this I made a public GameObject that I then put my model with all its scripts attached into. After that you just instantiate from that public GameObject so that the original GameObject is never destroyed. If it is not that, it could be your spawn points are to low and they are getting stuck.
Your answer
![](https://koobas.hobune.stream/wayback/20220612074200im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Items not destroying. 1 Answer
Unable to re-spawn after colliding with enemy 1 Answer
Remove object from List after gameObject was destroyed in between Scene loads 1 Answer