In the past 2 days, I have spent some time to build up an application for the company I have been worked for previously. As a production company, we were using some multipliers for a majority group of products to provide a fast offers for customers. Like an excel sheet, I have decided to build an application for them. Since the production costs per kilogram varies many times (in Turkish Lira), the application needed to be designed in a way that we can update the costs per unit.

This require a saving and loading system within the device. Unlike the Insurance application (the application I have worked on, you can find it on my previous articles), this app does not require any connection to internet. Of course, it would not be efficient if the user inputs the costs each time they run the application. So, PlayerPrefs to the rescue!

PlayerPrefs is a class that basically allows us to transfer the data in between different gameplay sessions such as the level, settings, items etc. For detailed information, check out the Unity Manual from the link below:

If you take a look to the link above, you will realize that we can only use 3 variable types in PlayerPrefs class: int, float and string. Every log that we create is denoted with a “key”. Thus, HasKey method simply returns a bool result if a key with the provided name or not. You can also observe that storage location for each device has been provided within the link above.

To save a preference, we use the methods that start with “Set”. And, the methods start with “Get” are used to load a parameter.

In my application, I have created a method for the button click so that it will save the input values for each container:

int cost1;
PlayerPrefs.SetInt(“variableStoringName”, cost1);
...
PlayerPrefs.Save();

To save, we simply use “PlayerPrefs.Save()” method.

In the calculation screen, I have called them as follows:

int costToBeUsed;if(PlayerPrefs.HasKey(“variableStoringName”){costToBeUsed = PlayerPrefs.GetInt(“variableStoringName”);}

And that’s actually how easy it is to use PlayerPrefs class. I have tested it on an Android device and it works like a charm. The data remains as we arrange it on different runs. Of course, deleting and reinstalling the application will also delete the previous saves you have made.

Unity Developer