Created
March 10, 2021 08:31
-
-
Save Matthew-J-Spencer/c13ece35fac9400f3a3681d3a4a651aa to your computer and use it in GitHub Desktop.
A save manager for your Unity game. Tutorial: https://www.youtube.com/watch?v=Lt-AiGbHN9g
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SaveManager : MonoBehaviour { | |
public static SaveData SaveData; | |
private static string SavePath => $"{Application.persistentDataPath}/save.game"; | |
private BinaryFormatter _formatter = new BinaryFormatter(); | |
void Start() { | |
Load(); | |
} | |
public void Save() { | |
var json = JsonUtility.ToJson(SaveData); | |
using (var stream = new FileStream(SavePath,FileMode.Create)) { | |
_formatter.Serialize(stream,EncryptDecrypt(json)); | |
} | |
} | |
public void Load() { | |
if (!File.Exists(SavePath)) { | |
SaveData = new SaveData() { | |
Level = 1, | |
Music = true, | |
Sound = true, | |
Vibrate = true, | |
CurrentCharacter = CharacterType.Archer, | |
UnlockedCharacters = new List<CharacterType>() {CharacterType.Archer} | |
}; | |
Save(); | |
} | |
using (var stream = new FileStream(SavePath,FileMode.Open)) { | |
var data = (string)_formatter.Deserialize(stream); | |
SaveData = JsonUtility.FromJson<SaveData>(EncryptDecrypt(data)); | |
} | |
} | |
[MenuItem("Developer/Delete Saved Game")] | |
public static void DeleteSave() { | |
if(File.Exists(SavePath)) File.Delete(SavePath); | |
} | |
private static string EncryptDecrypt(string textToEncrypt) | |
{ | |
var inSb = new StringBuilder(textToEncrypt); | |
var outSb = new StringBuilder(textToEncrypt.Length); | |
for (var i = 0; i < textToEncrypt.Length; i++) | |
{ | |
var c = inSb[i]; | |
c = (char)(c ^ 129); | |
outSb.Append(c); | |
} | |
return outSb.ToString(); | |
} | |
} | |
public enum CharacterType { | |
Archer, | |
Warrior, | |
Magician | |
} | |
[Serializable] | |
public class SaveData { | |
public CharacterType CurrentCharacter; | |
public List<CharacterType> UnlockedCharacters; | |
public int Level; | |
public bool Sound; | |
public bool Music; | |
public bool Vibrate; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment