Object gets instantiated twice, why? Im going crazy.

I have a script that spawns a certain object (boss) if a object with a certain tag dies. Everything works completly fine, but only the “BossRanged” gets instantiated twice, the other ones only once, but why?
The script is only attached to the “boss objects” and they get destroyed after going under 0 health (see in code).

My code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BossStats : MonoBehaviour
{
    public GameObject BossTank;
    public GameObject BossRanged;
    public GameObject BossSeed;

    public float health = 2500f;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void TakeDamage(float amount)
    {
        health -= amount;

        if (health <= 0f)
        {
            Die();
        }

        void Die()
        {
            if (this.tag == "CasterBoss" && health <= 0)
            {
                Instantiate(BossTank, this.transform.position, this.transform.rotation);
                Destroy(this.gameObject);
            }
            
            if (gameObject != null && this.tag == "TankBoss" && health <= 0)
            {
                Instantiate(BossRanged, this.transform.position, this.transform.rotation);
                Destroy(this.gameObject);
            }

            if (gameObject != null && this.tag == "RangedBoss" && health <= 0)
            {
                Instantiate(BossSeed, this.transform.position, this.transform.rotation);
                Destroy(this.gameObject);
            }

            if (gameObject != null && this.tag == "SeedBoss" && health <= 0)
            {
                Destroy(this.gameObject);
            }
        }
    }
}

1 Answer

1

I tested your script and the following came out: any boss can appear twice if the TakeDamage() function is called twice in the same frame. That is, if the boss has only one health left, and the damage has been done several times (and their damage is more than the remaining lives of the boss), then the next boss will appear so many times.
_
SOLUTION: add variable bool isSpawnedNextBoss; at the beginning of the script. At the beginning of the TakeDamage() function, add this condition: if (isSpawnedNextBoss == true) { return; }, and in the Die() function add isSpawnedNextBoss = true; (at the beginning or at the end).

It worked! Thank you very much! ^^