Search Unity

Simple Local Data Storage

Discussion in 'Community Learning & Teaching' started by RobAnthem, May 1, 2017.

  1. RobAnthem

    RobAnthem

    Joined:
    Dec 3, 2016
    Posts:
    90
    Storing Local Data - PlayerPrefs and Serialization

    Part 1 - Intro to PlayerPrefs
    PlayerPrefs is intended to store Preferences or Options, however it provides us a reasonable 3mb storage cache that is internally built-in to Unity so we can actually store data without access to the local devices file-system or a server. This is very useful when attempting to store small amounts of data. The main limitation of PlayerPrefs is that it can only store very specifci types of data. The folowing data types can be stored this way:
    1. Int (Integer data, being only whole numbers).
    2. Float (Floating Point number which can be positive, negative, or contain decimals).
    3. String (A set of characters comprising a string or word).
    As you can see these primitive data types can be a bit restricting because they will not allow us to store complex objects, however most complex objects are comprised of these simple data types. If used creatively, you can store nearly anything this way. As well one of the main bonuses to using PlayerPrefs is that the Application can store data on a mobile device without requesting storage access.
    PlayerPrefs has two main functions for each data type, being Get and Set, which act very much like a Dictionary because they use a string as the key. An example usage of setting a PlayerPref would look like this.

    Code (CSharp):
    1. PlayerPrefs.SetInt("myPref", 5);
    And an example of getting the data from PlayerPrefs would look like this.

    Code (CSharp):
    1. myint = PlayerPrefs.GetInt("myInt");
    Which can be overloaded to include a default parameter if none has been assigned, like this.

    Code (CSharp):
    1. myint = PlayerPrefs.GetInt("myInt", 5);
    As you can see, using PlayerPrefs is very simple. Next we will discuss how to use the effectively to store Player data.

    Part 2 - Using PlayerPrefs Effectively

    Now we just discussed how PlayerPrefs works, but before we can use it effectively we need to understand Getting/Setting.
    Every attribute or field if you will, that is contained in a class has a built-in GET and SET function that is called whenever it is either referenced, or being set. We are going to take advantage of these functions and basically turn our Player attributes into references to PlayerPrefs. So for our example, lets assume our Player has the following attributes.
    A Name (being a string).
    Experience (being an integer).
    A Level (being an integer).
    An amount of money (being a float, we'll use the decimals as change).
    So we will representing each one of these in our Player class. Normally these would be represented in a simple manner like this.
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. namespace MyProject
    4. {
    5.     public class Player
    6.     {
    7.         public string Name;
    8.         public int Level;
    9.         public int Experience;
    10.         public float Money;
    11.     }
    12. }
    This is the simplest way of representing these attributes in the Player class, but we will need to alter them to become purely reference attributes, and we will create a set of constant strings to represent each attributes key. So to make it simpler, we'll add each constant string above the actual attribute like so.
    private const string name = "Name";
    public string Name;
    Then we will want to extend each attribute to have a get and set function that actually calls to PlayerPrefs, like so.
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. namespace MyProject
    4. {
    5.     public class Player
    6.     {
    7.         private const string name = "Name";
    8.         public string Name
    9.         {
    10.             get { return PlayerPrefs.GetString(name); }
    11.             set { PlayerPrefs.SetString(name, value); }
    12.         }
    13.         private const string level = "Level";
    14.         public int Level
    15.         {
    16.             get { return PlayerPrefs.GetInt(level, 1); }
    17.             set { PlayerPrefs.SetInt(level, value); }
    18.         }
    19.         private const string exp = "Experience";
    20.         public int Experience
    21.         {
    22.             get { return PlayerPrefs.GetInt(exp); }
    23.             set { PlayerPrefs.SetInt(exp, value); }
    24.         }
    25.         private const string money = "Money";
    26.         public float Money
    27.         {
    28.             get { return PlayerPrefs.GetFloat(money); }
    29.             set { PlayerPrefs.SetFloat(money, value); }
    30.         }
    31.     }
    32. }
    Another way would be to use PlayerPrefs as a sort of Save/Load Method, and have the ability to save multiple versions of the Player, simply by passing an integer of a save slot, like this.
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. namespace MyProject
    4. {
    5.     public class Player
    6.     {
    7.         private const string name = "Name";
    8.         public string Name;
    9.         private const string level = "Level";
    10.         public int Level;
    11.         private const string exp = "Experience";
    12.         public int Experience;
    13.         private const string money = "Money";
    14.         public float Money;
    15.         public void Save(int SaveSlot)
    16.         {
    17.             PlayerPrefs.SetString("SaveSlot_" + SaveSlot.ToString() + "_" + name, Name);
    18.             PlayerPrefs.SetInt("SaveSlot_" + SaveSlot.ToString() + "_" + level, Level);
    19.             PlayerPrefs.SetInt("SaveSlot_" + SaveSlot.ToString() + "_" + exp, Experience);
    20.             PlayerPrefs.SetFloat("SaveSlot_" + SaveSlot.ToString() + "_" + money, Money);
    21.         }
    22.         public void Load(int SaveSlot)
    23.         {
    24.             Name = PlayerPrefs.GetString("SaveSlot_" + SaveSlot.ToString() + "_" + name, Name);
    25.             Level = PlayerPrefs.GetInt("SaveSlot_" + SaveSlot.ToString() + "_" + level, Level);
    26.             Experience = PlayerPrefs.GetInt("SaveSlot_" + SaveSlot.ToString() + "_" + exp, Experience);
    27.             Money = PlayerPrefs.GetFloat("SaveSlot_" + SaveSlot.ToString() + "_" + money, Money);
    28.         }
    29.     }
    30. }
    As you can see, we are utilizing the key string a little more in-depth by adding the slot and the attribute name to get the attribute itself. There are other ways of utilizing PlayerPrefs, but I hope this helps you to understand how it can be used to save simple data in an effective and easy way. Of course, this is not always enough, sometimes you need to save entire objects or a current state of the game. Which brings us to our next section.

    Part 3 - Serializing Complex Objects

    There are many types of serialization, but we are going to choose the most common type known as Binary Serialization. We will be serializing and deserializing our objects from the file-system. Effectively saving and loading the state of the object. Another effective use of a Binary Formatter is the ability to clone objects with it, you can serialize, and then deserialize an object, effectively creating a completely seperate copy.
    For this example, lets go back to the basic Player class, with one addition, we will add [Serializable] above the class name.
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. namespace MyProject
    5. {
    6.     [Serializable]
    7.     public class Player
    8.     {
    9.         public string Name;
    10.         public int Level;
    11.         public int Experience;
    12.         public float Money;
    13.     }
    14. }
    This is what allows us to Serialize the object, otherwise we will get an error from attempting to serialize and object not marked as [Serializable].
    Because we won't be needing our serializer constantly, we will make a new object to handle the process that we can create when needed.
    This class will contain a Save and Load method, which create a temporary Binary Formatter, and a FileStream. An important thing to note about a FileStream is that is must be closed with a Close() call, to free up the resources.

    Code (CSharp):
    1. using System;
    2. using System.IO;
    3. using System.Runtime.Serialization.Formatters.Binary;
    4. using UnityEngine;
    5.  
    6. namespace MyProject
    7. {
    8.     public class StorageHandler
    9.     {
    10.         /// <summary>
    11.         /// Serialize an object to the devices File System.
    12.         /// </summary>
    13.         /// <param name="objectToSave">The Object that will be Serialized.</param>
    14.         /// <param name="fileName">Name of the file to be Serialized.</param>
    15.         public void SaveData(object objectToSave, string fileName)
    16.         {
    17.             // Add the File Path together with the files name and extension.
    18.             // We will use .bin to represent that this is a Binary file.
    19.             string FullFilePath = Application.persistentDataPath + "/" + fileName + ".bin";
    20.             // We must create a new Formattwr to Serialize with.
    21.             BinaryFormatter Formatter = new BinaryFormatter();
    22.             // Create a streaming path to our new file location.
    23.             FileStream fileStream = new FileStream(FullFilePath, FileMode.Create);
    24.             // Serialize the objedt to the File Stream
    25.             Formatter.Serialize(fileStream, objectToSave);
    26.             // FInally Close the FileStream and let the rest wrap itself up.
    27.             fileStream.Close();
    28.         }
    29.         /// <summary>
    30.         /// Deserialize an object from the FileSystem.
    31.         /// </summary>
    32.         /// <param name="fileName">Name of the file to deserialize.</param>
    33.         /// <returns>Deserialized Object</returns>
    34.         public object LoadData(string fileName)
    35.         {
    36.             string FullFilePath = Application.persistentDataPath + "/" + fileName + ".bin";
    37.             // Check if our file exists, if it does not, just return a null object.
    38.             if (File.Exists(FullFilePath))
    39.             {
    40.                 BinaryFormatter Formatter = new BinaryFormatter();
    41.                 FileStream fileStream = new FileStream(FullFilePath, FileMode.Open);
    42.                 object obj = Formatter.Deserialize(fileStream);
    43.                 fileStream.Close();
    44.                 // Return the uncast untyped object.
    45.                 return obj;
    46.             }
    47.             else
    48.             {
    49.                 return null;
    50.             }
    51.         }
    52.     }
    53. }
    This will act as a creatable object that can be used to the purpose of saving and loading. This should be called from a location outside the player class, it is usually best to have some sort of maangement class, you could easily have a static management class that contains your data objects and the methods to save and load them. For example:

    Code (CSharp):
    1. namespace MyProject
    2. {
    3.     public static class GameManager
    4.     {
    5.         /// <summary>
    6.         /// Current player of this instance of game.
    7.         /// </summary>
    8.         public static Player player
    9.         {
    10.             // Default retrieval call
    11.             get
    12.             {
    13.                 if (_player == null)
    14.                 {
    15.                     StorageHandler storageHandler = new StorageHandler();
    16.                     _player = (Player)storageHandler.LoadData("player");
    17.                     if (_player == null)
    18.                     {
    19.                         _player = new Player();
    20.                     }
    21.                 }
    22.                 return _player;
    23.             }
    24.             // Default defining call
    25.             set
    26.             {
    27.                 _player = value;
    28.             }
    29.         }
    30.         private static Player _player;
    31.         /// <summary>
    32.         /// Save Player data to the file system
    33.         /// </summary>
    34.         private static void Save()
    35.         {
    36.             StorageHandler storageHandler = new StorageHandler();
    37.             storageHandler.SaveData(player, "player");
    38.         }
    39.     }
    40. }
    Now you see how easy it is to use our saving and loading system. This system can be used to save and load any Serializable object that you have. If a serializable object contains an attribute that is another object, that object must also be

    This is just one example of using Serialization to store data, but this works on all devices. You need to make sure that for mobile devices, you request access to the
    card, even if it doesn't have one, this is what defines that our app has access to read and write.
    Between these 2 methods of storing data, you should have no problem saving your players progress! May the code be with you, and I hope you enjoyed this tutorial.
     
    Last edited: May 2, 2017
    nekowei, Wumme51, salmonslay and 2 others like this.
  2. eduGigigo

    eduGigigo

    Joined:
    Apr 2, 2018
    Posts:
    2
    Hi, its posible serialize a AssetBundle and save in your Player model??

    Thx
     
  3. greggman

    greggman

    Joined:
    Nov 30, 2013
    Posts:
    24
    I'd look into using json (via DeJSON) and serialize/deserialize to a string and then store that string in PlayerPrefs. Writing a file won't work in the browser (unless unity has magically wrapped C#'s FileStream)
     
    NeneChico likes this.