Unity: Save and Load Data

Prerequisites

Which method should I choose?

Method 1: Using PlayerPrefs

2 UI Buttons on screen
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameSceneController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{

}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameSceneController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{

}
public void ClickOptionA()
{
PlayerPrefs.SetInt("selected_option", 1);
PlayerPrefs.Save();
SceneManager.LoadScene("SecondScene");
}
public void ClickOptionB()
{
PlayerPrefs.SetInt("selected_option", 2);
PlayerPrefs.Save();
SceneManager.LoadScene("SecondScene");

}
}
New scene with a UI Text
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SecondSceneController : MonoBehaviour
{
public Text bigText;
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{

}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SecondSceneController : MonoBehaviour
{
public Text bigText;
// Start is called before the first frame update
void Start()
{
int selected = PlayerPrefs.GetInt("selected_option");
if(selected == 1)
{
bigText.text = "Selected Option A";
} else if(selected == 2)
{
bigText.text = "Selected Option B";
}

}
// Update is called once per frame
void Update()
{

}
}
Link up the Text
Make sure the 2 scenes are in the the “Scenes in Build” section

Method 2: Using Serialization and Deserialization

Serialization is to convert an object (e.g. game object) into a series of bytes, which can be saved in either memory, file or database.

Deserialization is to convert the series of bytes back to an object.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Save
{

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Save
{
// Simple variable
public int score = 0;
// Complex variable
public List<Vector2> targets = new List<Vector2>();

}
Our “Enemy 1”
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
private int scoreObtained = 0;
public GameObject enemies;
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
RandomPosition();
}

}
private void RandomPosition()
{
for (int i = 0; i < enemies.transform.childCount; i++)
{
enemies.transform.GetChild(i).transform.position = new Vector3(Random.Range(-2, 14), Random.Range(-3, 5), 0);
}
scoreObtained = Random.Range(100, 10000);
}

}
Drag the enemies game object from Hierarchy panel
using System.Runtime.Serialization;
using UnityEngine;
sealed class Vector3SerializationSurrogate : ISerializationSurrogate
{
// Method called to serialize a Vector3 object
public void GetObjectData(System.Object obj,
SerializationInfo info, StreamingContext context)
{
Vector3 v3 = (Vector3)obj;
info.AddValue("x", v3.x);
info.AddValue("y", v3.y);
info.AddValue("z", v3.z);
Debug.Log(v3);
}
// Method called to deserialize a Vector3 object
public System.Object SetObjectData(System.Object obj,
SerializationInfo info, StreamingContext context,
ISurrogateSelector selector)
{
Vector3 v3 = (Vector3)obj;
v3.x = (float)info.GetValue("x", typeof(float));
v3.y = (float)info.GetValue("y", typeof(float));
v3.z = (float)info.GetValue("z", typeof(float));
obj = v3;
return obj;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
private int scoreObtained = 0;
public GameObject enemies;
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{

}
private Save CreateSaveFile()
{
Save save = new Save();
// Handling simple variable "score"
save.score = scoreObtained;
// Handling complex variable
// Obtain the position of each child in the "enemies" game object.
for(int i = 0; i < enemies.transform.childCount; i++)
{
save.targets.Add(gameObject.transform.GetChild(i).transform.position);
}
return save;
}

}
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public void SaveGame()
{
Save save = CreateSaveFile();
SurrogateSelector surrogateSelector = new SurrogateSelector();
surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), new Vector3SerializationSurrogate());
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.SurrogateSelector = surrogateSelector;
FileStream file = File.Create(Application.persistentDataPath + "/game.save");
binaryFormatter.Serialize(file, save);
file.Close();
Debug.Log("Game saved");
}
public void LoadGame()
{
if(File.Exists(Application.persistentDataPath + "/game.save"))
{
SurrogateSelector surrogateSelector = new SurrogateSelector();
surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), new Vector3SerializationSurrogate());
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.SurrogateSelector = surrogateSelector;
FileStream file = File.Open(Application.persistentDataPath + "/game.save", FileMode.Open);
Save save = (Save)binaryFormatter.Deserialize(file);
file.Close();
for(int i = 0; i < save.targets.Count; i++)
{
enemies.transform.GetChild(i).transform.position = save.targets[i];
}
scoreObtained = save.score; Debug.Log("Game loaded");
} else {
Debug.Log("No save file is found");
}
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space)) {
RandomPosition();
} else if(Input.GetKeyDown(KeyCode.S)) {
SaveGame();
} else if (Input.GetKeyDown(KeyCode.L)) {
LoadGame();
}
}

Try out the Game

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store