How to save and load an integer with PlayerPrefs in Unity

Introduction

We’re going to see how to save integer numbers in Unity using the PlayerPrefs class, then we’ll see how to load those numbers in Unity. This method will be useful for example to save the score in Unity, if that score is represented by an integer number of course.

How to save an integer with PlayerPrefs

To save an integer in Unity using PlayerPrefs we’ll use the static method “SetInt”, a function that needs two parameters.

The first parameter is a string with the name that will have this variable that we are going to store, this will allow that later we can recover it. The second parameter is the integer value that we want to store.

The instruction that will do the saving of the data in Unity would look like this:

PlayerPrefs.SetInt(“integerDataName”,integerNumber);

In this case we indicate the name of the data between quotes because it’s a string, the second parameter we indicate it using an int type variable.

How to load an integer with PlayerPrefs

To load an integer into Unity using PlayerPrefs we’ll use the static “GetInt” method, a function that can be used in two different ways.

In the first form we give a parameter that is going to be the name of the data we want to retrieve, the name we gave it when we executed the “SetInt” function we saw before. We do it in the following way.

integerNumber=PlayerPrefs.GetInt(“integerDataName”);

The execution of the static method “GetInt” of PlayerPrefs results in an integer, that’s why it is assigned to the variable “integerNumber” in the above instruction.

The second way is also to give it the name of the data that we use in the execution of “SetInt” but we also give a default value that will be used in case there is no data saved under that name, this is done in the following way.

integerNumber =PlayerPrefs.GetInt(“integerDataName”,0);

Scroll to Top
Secured By miniOrange