Litlle problem with DontDestroyOnLoad().

Basicly I was needing something to move my HP points between two scenes. I managed to do that by using the DontDestroyOnLoad method. However, it work’s great. But there is one issue which i can’t handle.

When I go to arena Scene, everything is fine and working. But when I go back to my main scene, I’m getting two copies of these objecs.
Here are my scripts :

saveManager - Pastebin.com saveManager.

This script makes me able to move those values between scenes.

SaveFinder - Pastebin.com SaveFinder.

This script is loking for object with savemanager script and playerhealth script to help them find objects with my health and text to show to to player.

playerhealth - Pastebin.com playerhealth.

This script is working on players hp and it is showing it on canvas.

Hope I’ve explained it well enought :slight_smile:

Thanks in advance :slight_smile:

@dowak23

this will make sure that this is the only script of its type in the scene and if you need to access health from another script just type PlayerHealth.instance.health in the other script

using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour
{
    public static PlayerHealth instance;
    public int health;

    void Awake()
    {
        if(instance == null)
        {
            instance = this;
        }

        else if(instance != null)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }

	void Start ()
    {
	    
	}

	void Update ()
    {
	    
	}
}

Instead of Destroying try disabling any script with the same MonoBehavior ._. I have no actuall code for that, but it will work.

make your health bar to be a prefab with a dont destroy on load.
instantiate it 1 time from code and you will be 100% to never have any conflict because of Start order or OnLevelWasLoaded execution order

i dont really like the singleton kind of approach for that kind of thing.
The singleton pattern is great but way to often badly used