Player not deleting

Hello,

I am trying to get my scene changing working. but for some reason my player is not correctly deleted.

    private static bool Exists; 

    void Start()
    {
        anim = GetComponent<Animator>();
        body = GetComponent<Rigidbody2D>();

        if(!Exists)
        {
            Exists = true;
            DontDestroyOnLoad(transform.gameObject);
        }
        else
            Destroy(gameObject);
    }

but when i run switch levels i have 2 players where 1 of them has all of its element set to NULL and is also not visible in the hierarchy. so after switching maps 100 times i have a lot of objects that i dont want.

any idea what i am doing wrong?

Roy

DontDestroyOnLoad (line 11) is the root of your problem, just like the name says, this method marks an object so it doesn’t get destroyed when loading a new scene (When changing scenes everything gets automatically destroyed, except of course for objects marked by DontDestroyOnLoading). That’s what is not allowing the player to be correctly deleted when changing scenes, so every time you change scene, this player won’t get destroyed and also there will be a new player spawned since that’s the content of the new scene, and that player will also not get destroyed and so on. The answer is simple, get rid of that line of code. However the real question is, why did you use DontDestroyOnLoad() in the first place?

If i dont use DontDestroyOnLoad(transform.gameObject); wont it delete any of lets say my items and gold because it makes a new version of my player?

Edit: also i am not spawning a new player in my other map so when i go to that one without DontDestroyOnLoad i have no player and no camera

If you are still looking to use this way, I use something similar. This is what I use (with Player being the Player gameObject). Also, use Awake() to make sure the existing one survives the scene change.

public static Player player;
void Awake(){
	if (player == null) {
		DontDestroyOnLoad (gameObject);
		player = this;
	} else if (player != this) {
		Destroy (gameObject);
	}