Hi, I’m very very new to Unity and especially unfamiliar with prefabs and how they work in Unity’s logic. So I’m making a shooter and when the bullet hits the enemy it plays a little sound and destroys the enemy. The enemy is a prefab and it works perfectly fine if there’s only one instance of it in the scene. However, if there’s more than one of the enemies in the scene it destroys them in order of last to first added, and it takes two hits to destroy the last one. I really don’t understand what’s going on here, does anyone understand?
Here is the code that runs when the bullet collides with the enemy.
public class LazerDamage : MonoBehaviour {
private TurretHealth turret;
private void Start()
{
turret = GameObject.FindGameObjectWithTag("Enemy").GetComponent<TurretHealth>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
turret.Damage(1);
Destroy(gameObject);
Debug.Log("Hit");
}
}
}
And here is the code that destroys the enemy (referred to as Turret in script)
public class TurretHealth : MonoBehaviour {
//Stats
public int curHealth;
public int maxHealth = 1;
private AudioSource source;
public AudioClip[] notes;
public Renderer rend;
bool hasplayed;
// Use this for initialization
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
curHealth = maxHealth;
hasplayed = false;
}
// Update is called once per frame
void Update()
{
if (curHealth > maxHealth)
{
curHealth = maxHealth;
}
if (curHealth <= 0)
{
Die();
}
}
void Die()
{
if (!hasplayed)
{
source = GetComponent<AudioSource>();
source.clip = notes[Random.Range(0, notes.Length)];
source.Play();
hasplayed = true;
rend.enabled = false;
Destroy(gameObject, source.clip.length);
}
}
public void Damage(int dmg)
{
curHealth -= dmg;
}
}