Skip to content

Instantly share code, notes, and snippets.

@gegagome
Created April 2, 2017 05:06
Show Gist options
  • Select an option

  • Save gegagome/618f2cccd01ebdd3b15eca5cd67b41fc to your computer and use it in GitHub Desktop.

Select an option

Save gegagome/618f2cccd01ebdd3b15eca5cd67b41fc to your computer and use it in GitHub Desktop.
Unity persistent data script
// basic persistant data saving and loading: https://unity3d.com/learn/tutorials/topics/scripting/persistence-saving-and-loading-data
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class IAPManager : MonoBehaviour {
public bool _isProductCleared = false;
bool _isPremium = false;
public Text _label;
const string FILE_PATH = "/playerInfo.dat";
public static IAPManager _iapManager;
void Awake () {
if (_iapManager == null) {
DontDestroyOnLoad (this.gameObject);
_iapManager = this;
} else if (_iapManager != this) {
Destroy (this.gameObject);
}
}
void Start () {
if (_isProductCleared) {
DeleteFile ();
}
Load ();
IAPStatus ();
}
public void IAPBought () {
_isPremium = true;
IAPStatus ();
Save ();
}
void IAPStatus () {
if (_isPremium) {
_label.text = "IAP Purchased\n";
} else {
_label.text = "-------------";
}
}
public void Save () {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + FILE_PATH);
PlayerData data = new PlayerData ();
data.isPremium = _isPremium;
bf.Serialize (file, data);
file.Close ();
}
public void Load () {
if (File.Exists ((Application.persistentDataPath + FILE_PATH))) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + FILE_PATH, FileMode.Open);
PlayerData data = bf.Deserialize (file) as PlayerData;
file.Close ();
_isPremium = data.isPremium;
}
}
public void DeleteFile () {
if (File.Exists ((Application.persistentDataPath + FILE_PATH))) {
File.Delete((Application.persistentDataPath + FILE_PATH));
_label.text = "-------------";
}
}
public bool IsPremium () {
if (_isPremium) {
IAPStatus ();
}
return _isPremium;
}
}
[Serializable]
class PlayerData {
public bool isPremium;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment