I am new to coding and I would like to know how to keep my object (coin) destroyed when the player collects it than dies and respawns which resets the scene and the coin comes back so the player can keep tallying his score up by dying.
here is my code for the coin
public AudioSource collectSound;
void OnTriggerEnter(Collider other)
ScoringSystem.theScore += 10;
and here is my code that makes the player respawn
void OnCollisionEnter(Collision collisionInfo)
if (collisionInfo.collider.tag == "obstacle")
movement.enabled = false;
here is my code for when the game restarts in my Gamemanager script
public void EndGame()
if (gameHasEnded == false)
gameHasEnded = true;
public void Restart()
There are different approaches:
It seems like the coin is inside your scene. So you could create e.g. a “GameManager”-singleton which keeps existing, when you swich between scenes ( DontDestroyOnLoad() ) . Or you can just simply use a static class (no Monobehaviour) for the same purpose. Then make e.g. a counter or a boolean to check, if you open the scene a second time (after the die) and then destroy the already collected coins on Awake().
For this approach, each Coin should probably have an id and your “GameManager” needs a List or Array, so that you know, which ones you have to destroy (when you not just want to destroy either none or all).
Alternatively you could take a similar approach, but don’t place the coins hard in the scene. You could just spawn the ones by script dynamically on runtime at scene start, which you really need. The other logic is similar to the first approach.
Another easier way you could do this, is to only make it appear that the player has died, but dont load a new scene, and just reset the position of your player to a spawn point.