#how to keep a destroyed game object destroyed after scene reload

1 messages · Page 1 of 1 (latest)

wispy dune
#

I have coins in my game as collectibles and Id like the coins to not come back after the character respawns/ the scene reloads

Ive found some forum posts regarding the topic but theyre all on the topic of more complex enemy controllers, Im just looking to make the "destroy gameobject" function last after scenes reload/change, any advice appreciated 🙂

public class Coin : MonoBehaviour
{

    public int value;


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

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

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            SoundManagerScript.PlaySound("pickup"); // PLAYS SOUND
            Destroy(gameObject);
            CoinCounter.instance.IncreaseCoins(value);
        }
    }
}


code for the coin^^

grave hill
wispy dune
#

I want the coin count to be retained when the player dies but the ones theyve already collected to not be collectable again

#

because the end of the level trigger event happens at 50 coins

#

so they need to retain them but also I dont want the player to be able to just recollect coins theyve already collected after respawning

grave hill
#

As an option, you can make smth like "CoinManager" which will save the state of all your coins on the map in a static array.

exotic cargo
# wispy dune I have coins in my game as collectibles and Id like the coins to not come back ...

this is hard, because when you load the new scene, all coins are basically new objects

so you need a way to identify coins that are on the same position for different scene loads of the same scene,
for example, if each coin has a unique name in the hierarchy, you could store the hierarchy path of the collected coins,
then when loading the same scene again, you check every scene object `(for example with FindObjectsOfType<Transform>() or with a recursive solution like i have here https://gist.github.com/FleshMobProductions/c221b28a5cb11adee38bbc6dc16e39a6 at the start of HighlightReferencingObjects)

it would be easier perhaps to store the coins not as scene objects but only store positions and number in a file like a json that you can load,
then each coin could also have a bool whether it was collected or not and you only spawn coin from prefabs that havenot been collected