Player Prefs for Current Lives

Could someone please explain to me how I can keep the current lives onto all my other scenes within the game I’m creating. I think I need player prefs but not sure how to implement this…?

using UnityEngine;
using System.Collections;

public class Lives : MonoBehaviour
{

		// Need this for singleton
		public static Lives Instance { get; private set; }

		public int startingLives = 3;
		public static int curLives;

		// Need this for singleton
		void Awake ()
		{
				if (Instance == null) {
						Instance = this;
				} else {
						Destroy (gameObject);
				}
				}
	
		// Use this for initializatio		n
		void Start ()
		{
				curLives = startingLives;
		}
	
		// Update is called once per frame
		void Update ()
		{
				guiText.text = "Lives:" + curLives.ToString ();
		}

		// New method to decrementLives
		public void decrementLives ()
		{
				curLives--;
		}
	// Increment Lives
		public void incrementLives ()
		{
				curLives++;
		}
}

Here is a save script!

using UnityEngine;
using System.Collections;

public class SaveScript : MonoBehaviour {
	public static SaveScript instance;

	void Awake(){
		if(instance == null)
			instance = this as SaveScript;
		else
			Destroy(this);
	}
	public void Save(int lifes){
		PlayerPrefs.SetInt("Life", lifes);
	}
	public int Load(){
		return PlayerPrefs.GetInt("Life");
	}
}

Then you call this in your other code when you want to save / load. Example: (Load in Start() and Save before you load next map.

So in Start you do:

void Start(){
curLives = SaveScript.instance.Load();
}

And when you want to save you do:

SaveScript.instance.Save(curLives);

Hope that made sense and was of use!

You can simplify your script quite a bit since it doesn’t need to be a MonoBehaviour at all :wink:

public class Lives
{
    private static int m_InitialLives = 3;
    private static int m_CurLives;
    // static constructor
    static Lives()
    {
        m_CurLives = PlayerPrefs.GetInt("lives", m_InitialLives);
    }
    public static int CurLives
    {
        get { return m_CurLives; }
        set
        {
            m_CurLives = Mathf.Max(0, value); // clamp so it can't get negative
            PlayerPrefs.SetInt("lives", m_CurLives);
        }
    }
}

With this class you can access your current lives from everywhere like this:

    // read
    if(Lives.CurLives > 0)
    
    // decrement
    Lives.CurLives--;
    
    // increment
    Lives.CurLives++;
    Lives.CurLives+= 5;
    
    // set
    Lives.CurLives= 10;

It will be initialized with “m_InitialLives” the first time you access this script. Everytime you change the value it’s stored in the PlayerPrefs so the next time you start your game it will load the last value.