简体   繁体   中英

Unity C#, 2D game Spawning loot at selected location

Im currently making 2D game space shooter like game in unity. My issue is with the Loot spawning script. If enemies spawn at fast rate then loot will spawn not at the destroyed enemy but one of the ones that just spawned.

The 2 Scripts that are used for all my detection and loot spawning:

public void onDeath(bool isDead)
{
    if (isDead == true)
    {
        if (Random.value <= dropProbability)
        {
            Instantiate(Loot.transform, Loot.transform.position = Enemy.transform.position, Quaternion.Euler(0, 180, 0));
        }
    }
}

This script takes in 2 game objects first is for my loot and second the enemy. I instantiate my loot on position of my enemy.

void Update()
{
    if (healthPoints <= 0)
    {
        if (gameObject.CompareTag("Enemy"))
        {
            FindObjectOfType<LootSpawn>().onDeath(true);
            Destroy(this.gameObject);
        }
        else
        {
            Destroy(this.gameObject);
        }
    }      
}

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Ammo") != true)
    {
        if (other.gameObject.tag != this.gameObject.tag)
        {
            healthPoints--;
            if (other.gameObject.CompareTag("Player1") == true)
            {
                FindObjectOfType<uiElements>().RemoveHealth();
            }
        }
    }
}

This is the global script that I use for "ALL" detection this includes bullets, player and enemy. The script works fine when spawn interval between each enemy is higher than 2.5seconds anything less causes this issue I'll attach 2 screenshot to visually show my issue Before The Shot , After Shot

Finally to clarify I want my "Loot" to always spawn at the "Destroyed" Enemy regardless of how many enemies are on field or how fast they are instantiated onto the field. Without making my code much longer and making it messy can anyone point me in right direction? would greatly appreciate.

Benjamin Danger Johnson what you said is correct, this is one year old question though. I believe what you said was actually the solution. I have long since solved this issue (and looking now I find it weird how I struggled with it hehe, but progress makes us better I guess).

For anyone would ever have similar issue. Dont use FindObjectOfType Use unity's GetComponent instead: https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM