Skip to content

Instantly share code, notes, and snippets.

@mamadDev
Created January 15, 2021 17:58
Show Gist options
  • Save mamadDev/1d1cb0b2347ca78de7c3713a6b134bac to your computer and use it in GitHub Desktop.
Save mamadDev/1d1cb0b2347ca78de7c3713a6b134bac to your computer and use it in GitHub Desktop.
Demo of how to store text or save data in unity
using UnityEngine;
using System.IO;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
public class SaveDemo : MonoBehaviour
{
private void OnGUI()
{
GUIStyle customButton = new GUIStyle("button");
customButton.fontSize = 50;
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.1f, Screen.width * 0.5f, Screen.height * 0.05f), "Player Pref Save", customButton))
{
PlayerPrefsSave();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.15f, Screen.width * 0.5f, Screen.height * 0.05f), "Player Pref Load", customButton))
{
PlayerPrefsLoad();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.2f, Screen.width * 0.5f, Screen.height * 0.05f), "Stream Writer Save",customButton))
{
StreamWriterSave();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.25f, Screen.width * 0.5f, Screen.height * 0.05f), "Stream Reader Load", customButton))
{
StreamReaderLoad();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.3f, Screen.width * 0.5f, Screen.height * 0.05f), "Binary Writer Save", customButton))
{
BinaryWriterSave();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.35f, Screen.width * 0.5f, Screen.height * 0.05f), "Binary Reader Load", customButton))
{
BinaryReaderLoad();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.4f, Screen.width * 0.5f, Screen.height * 0.05f), "Binary Formatter Save", customButton))
{
BinaryFormatterSave();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.45f, Screen.width * 0.5f, Screen.height * 0.05f), "Binary Formatter Load", customButton))
{
BinaryFormatterLoad();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.5f, Screen.width * 0.5f, Screen.height * 0.05f), "JSon Utility Save", customButton))
{
JSonUtilitySave();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.55f, Screen.width * 0.5f, Screen.height * 0.05f), "JSon Utility Load", customButton))
{
JSonUtilityLoad();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.6f, Screen.width * 0.5f, Screen.height * 0.05f), "Encrypt JSon Save", customButton))
{
encrytJSonSave();
}
if (GUI.Button(new Rect(Screen.width * 0.25f, Screen.height * 0.6f, Screen.width * 0.5f, Screen.height * 0.05f), "Decrypt JSon Load", customButton))
{
decrytJSonLoad();
}
}
/*
* Playerprefs Location
* Windows:- Registry Editor - Computer\HKEY_CURRENT_USER\SOFTWARE\Unity\UnityEditor\Company Name\Project name
*/
void PlayerPrefsSave()
{
PlayerPrefs.SetInt("Test Int Pref", 1);
PlayerPrefs.SetFloat("Test Float Pref", 1.0f);
PlayerPrefs.SetString("Test String Pref", "One");
PlayerPrefs.Save();
Debug.Log("PlayerPrefs Saved");
}
void PlayerPrefsLoad()
{
if(!PlayerPrefs.HasKey("Test Int Pref") || !PlayerPrefs.HasKey("Test Float Pref") || !PlayerPrefs.HasKey("Test String Pref"))
{
return;
}
int numInt = PlayerPrefs.GetInt("Test Int Pref");
float numFloat = PlayerPrefs.GetFloat("Test Float Pref");
string numString = PlayerPrefs.GetString("Test String Pref");
Debug.LogFormat("PlayerPrefs Load:{0}-{1}-{2}",numInt,numFloat,numString);
}
/*
* Persistent DataPath Location
* Windows:- C:\Users\<userprofile>\AppData\LocalLow\<companyname>\<productname>
* mac:- ~/Library/Application Support/companyname/productname
*/
void StreamWriterSave()
{
string saveFilePath = Path.Combine(Application.persistentDataPath, "savegame.sav");
StreamWriter sw = new StreamWriter(saveFilePath);
sw.WriteLine("Hello, World!");
sw.Close();
Debug.Log("StreamWriter Saved");
}
void StreamReaderLoad()
{
string loadFilePath = Path.Combine(Application.persistentDataPath, "savegame.sav");
StreamReader sr = new StreamReader(loadFilePath);
string line = sr.ReadLine();
sr.Close();
Debug.Log("StreamReader Load:"+ line);
}
void BinaryWriterSave()
{
string saveFilePath = Path.Combine(Application.persistentDataPath, "savegameB.sav");
FileStream fs = new FileStream(saveFilePath,FileMode.OpenOrCreate);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write("Hello World");
bw.Write(1);
bw.Write(1.0f);
bw.Close();
fs.Close();
Debug.Log("BinaryWriter Saved");
}
private void BinaryReaderLoad()
{
string loadFilePath = Path.Combine(Application.persistentDataPath, "savegameB.sav");
FileStream fs = new FileStream(loadFilePath, FileMode.OpenOrCreate);
BinaryReader br = new BinaryReader(fs);
Debug.Log("BinaryReader Load:"+br.ReadString()+br.ReadInt32());
br.Close();
fs.Close();
}
[System.Serializable]
private class DataContainer
{
public string name;
public int mana;
public float health;
}
private void BinaryFormatterSave()
{
string saveFilePath = Path.Combine(Application.persistentDataPath, "savegameBF.sav");
DataContainer data = new DataContainer();
data.name = "Test Name";
data.mana = 200;
data.health = 100f;
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(saveFilePath, FileMode.OpenOrCreate);
Debug.Log("Data Formatter Saved");
bf.Serialize(fs, data);
fs.Close();
}
private void BinaryFormatterLoad()
{
string loadFilePath = Path.Combine(Application.persistentDataPath, "savegameBF.sav");
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(loadFilePath, FileMode.OpenOrCreate);
DataContainer data = bf.Deserialize(fs) as DataContainer;
Debug.LogFormat("Load Binary Formatter:{0}-{1}-{2}",data.name,data.mana,data.health);
fs.Close();
}
private void JSonUtilitySave()
{
string saveFilePath = Path.Combine(Application.persistentDataPath, "JSonUtilityData.sav");
DataContainer data = new DataContainer();
data.name = "Test Name";
data.mana = 200;
data.health = 100f;
string _json = JsonUtility.ToJson(data);
File.WriteAllText(saveFilePath, _json);
Debug.Log("JSon Data:" + _json);
}
private void JSonUtilityLoad()
{
string loadFilePath = Path.Combine(Application.persistentDataPath, "JSonUtilityData.sav");
string _data = File.ReadAllText(loadFilePath);
//DataContainer data = new DataContainer();
//JsonUtility.FromJsonOverwrite(_data, data);
//or
DataContainer data = JsonUtility.FromJson<DataContainer>(_data);
Debug.LogFormat("Loaded JSon Data:{0}-{1}-{2}",data.name,data.mana,data.health);
}
byte[] _key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] _initializationVector = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] Encrypt(string message)
{
AesManaged aes = new AesManaged();
ICryptoTransform encryptor = aes.CreateEncryptor(_key,_initializationVector);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);
StreamWriter streamWriter = new StreamWriter(cryptoStream);
streamWriter.WriteLine(message);
streamWriter.Close();
cryptoStream.Close();
memoryStream.Close();
return memoryStream.ToArray();
}
string Decrypt(byte[] message)
{
AesManaged aes = new AesManaged();
ICryptoTransform decryptor = aes.CreateDecryptor(_key, _initializationVector);
MemoryStream memoryStream = new MemoryStream(message);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
StreamReader streamReader = new StreamReader(cryptoStream);
string decryptorMessage = streamReader.ReadToEnd();
memoryStream.Close();
cryptoStream.Close();
streamReader.Close();
return decryptorMessage;
}
private void encrytJSonSave()
{
string saveFilePath = Path.Combine(Application.persistentDataPath, "JSonEncryptData.sav");
DataContainer data = new DataContainer();
data.name = "Test Name";
data.mana = 200;
data.health = 100f;
string _json = JsonUtility.ToJson(data);
byte[] encryptedSaveJson = Encrypt(_json);
File.WriteAllBytes(saveFilePath, encryptedSaveJson);
Debug.Log("JSon Data:" + _json);
}
private void decrytJSonLoad()
{
string loadFilePath = Path.Combine(Application.persistentDataPath, "JSonEncryptData.sav");
byte[] decryptedSaveGame = File.ReadAllBytes(loadFilePath);
string jsonString = Decrypt(decryptedSaveGame);
DataContainer data = JsonUtility.FromJson<DataContainer>(jsonString);
Debug.LogFormat("Loaded JSon Data:{0}-{1}-{2}", data.name, data.mana, data.health);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment