How to save and load a float variable with PlayerPrefs in Unity

Introduction

We’re going to see how to store floats in Unity using the PlayerPrefs class, then we’ll see how to load those float values.

This can be useful, for example, to save configuration parameters that has decimal values.

How to save a float with PlayerPrefs

To save a float in Unity using PlayerPrefs we’ll use the static method “SetFloat”, 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 float value that we want to store.

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

PlayerPrefs.SetFloat(“floatDataName”,floatNumber);

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

How to load a float with PlayerPrefs

To load a float into Unity using PlayerPrefs we’ll use the static “GetFloat” 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 “SetFloat” function we saw before. We do it in the following way.

floatNumber=PlayerPrefs.GetString(“floatDataName”);

The execution of the static method “GetFloat” of PlayerPrefs results in a float value, that’s why it is assigned to the variable “floatNumber” in the above instruction.

The second way is also to give it the name of the data that we use in the execution of “SetFloat” 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.

floatNumber=PlayerPrefs. GetString(“floatDataName”,0f);

Leave a Comment

Your email address will not be published. Required fields are marked *