Refining the save and load system

If you want to be more sophisticated with your save and load system, then you will need three more functions.

The first one checks whether a save slot is available in the memory or not. Although you can implement this functionality within the load function (for example, returning null), for the sake of simplicity, we will create a separate function that returns a Boolean indicating whether the slot is available or not. This is useful when you need to show to the player which slots are empty or which ones are taken. The function is really simple, it just needs to check whether the key passed as a parameter exists. We can do this by checking only one of the data, which we have prefixed with the key.. In fact, if we do things right, we should have incomplete saving slots in which just partial information is available. Thus, here is the function:

   public static bool HasSlot(string slotKey) {
//Check whether the slotkey exist
return PlayerPrefs.HasKey(slotKey + "_level");
}

Another useful function deletes a specific save slot. This can be done by taking in input the key and erasing all the items related to that slot. Here, you need to be sure to erase them all, especially if you don't want to have a problem with the function HasSlot():

   public static void DeleteSlot(string slotKey) {
//Delete the whole slot, item by item
PlayerPrefs.DeleteKey(slotKey + "_level");
PlayerPrefs.DeleteKey(slotKey + "_positionX");
PlayerPrefs.DeleteKey(slotKey + "_positionY");
PlayerPrefs.DeleteKey(slotKey + "_score");
PlayerPrefs.DeleteKey(slotKey + "_time");
PlayerPrefs.DeleteKey(slotKey + "_playerName");
}

Finally, a function that clears all the slots might be useful. In this case, the only things you save with PlayerPrefs are the slots. Therefore, we can easily use DeleteAll(), as we are about to do. Otherwise, you need a loop that calls the DeleteSlot() function on each one of the slots. In our case, the function is just a wrapper for the DeleteAll() function:

   public static void DeleteAllSlots() {
//Delete all the PlayerPrefs
PlayerPrefs.DeleteAll();
}

Save the script and congratulate yourself, since now you have a working save and load system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset