because it never really was an issue previously, I would save character data using 8 or so different PlayerPrefs values. But I want to attempt to make an RPG, and the amount of data needed to save would be astronomically time wasting and complicated to save everything as a different value.
What I was thinking of doing, is saving it all as a single string of data, as an example if these were the characters stats:
Level 2
EXP 12
HP 23/30
Strength 4
Intelligence 5
Speed 3
Charisma 6
It would save a string labeled as “0212023030040503060”
Saving the string would be easy, but I do not have the know how to have the game distinguish what parts of the string it needs to fill out the stats. How can I do this, or better yet, is there an easier way to do it?
I don’t know if it’s a good approach or not but I achieve this as follows:
First I declare custom classes to hold all the info I want to persist. Note that each classe must be serializable (place the appropriate decoration before the declaration):
[System.Serializable]
public class MyGameState
{
public string idState;
public int language;
public List<int> listOfThings;
public List<GameItem> listOfItems;
public GameState()
{
// Initializations...
}
}
[System.Serializable]
public class MyGameItem
{
public int itemId;
public string itemName;
public int itemAmount;
...
}
After that, you can load and save the state of your game as follows:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;
public void saveMyGameFile()
{
// Create the saveState, it can be done wherever
MyGameState myGameState = new MyGameState();
mgs.language=2;
MyGameItem myItem = new MyGameItem();
myItem.itemName = "stuff";
myGameState.listOfItems = new List<MyGameItem>();
myGameState.listOfItems.Add(myItem);
...
// Save it to a file
string myFileName = "savedFile.abc";
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + "/" + myFileName);
bf.Serialize (file, myGameState);
file.Close ();
}
public void loadMyGameFile()
{
string myFileName = "savedFile.abc";
if (File.Exists (Application.persistentDataPath + "/" + myFileName)) {
// Load the game state
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" + myFileName, FileMode.Open);
MyGameState myGameState = new MyGameState();
myGameState = (MyGameState)bf.Deserialize(file);
file.Close();
// Using the data previously loaded
int currentLang = myGameState.language;
}
}
Note that this is just pseudocode and here I’m not using any type of data encryption. Hope it helps!
If you want to go down the serializing & BinaryFormatter road, take a look at SerializeHelper. It explains the whole procecudure in small steps and is a good base for your own save system (it’s also perfectly usable on it’s own).