Skip to content

Instantly share code, notes, and snippets.

@rocky1138
Last active October 8, 2016 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rocky1138/d90ec686715d3174ac58f570f36e7f79 to your computer and use it in GitHub Desktop.
Save rocky1138/d90ec686715d3174ac58f570f36e7f79 to your computer and use it in GitHub Desktop.
/**
* Transcribed from Persistence - Saving and Loading Data Tutorial video.
* Original code by Mike Geig.
* Transcribed by rocky1138.
* No idea on what the license is. I think it's fairly safe to assume public domain
* since it's part of a tutorial video.
* https://unity3d.com/learn/tutorials/topics/scripting/persistence-saving-and-loading-data
*/
using UnityEngine;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;
public class Player : MonoBehaviour {
public float health;
public float experience;
public void Save () {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.OpenOrCreate);
PlayerData data = new PlayerData ();
data.health = health;
data.experience = experience;
bf.Serialize (file, data);
file.Close ();
}
public void Load () {
if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.OpenOrCreate);
PlayerData data = (PlayerData) bf.Deserialize (file);
file.Close ();
health = data.health;
experience = data.experience;
}
}
}
[Serializable]
class PlayerData {
public float health;
public float experience;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment