Skip to content

Instantly share code, notes, and snippets.

@pajama
Last active November 27, 2017 22:34
Show Gist options
  • Save pajama/4bf2919db7e7ad5750616540b4f74c7a to your computer and use it in GitHub Desktop.
Save pajama/4bf2919db7e7ad5750616540b4f74c7a to your computer and use it in GitHub Desktop.
[Persistent] attribute that automatically saves/loads properties with PlayerPrefs
using UnityEngine;
using System;
using System.Reflection;
using Helios;
//this creates the [Persistent] attribute that can be applied before a property
[AttributeUsage(AttributeTargets.Property)]
public class PersistentAttribute : Attribute
{
}
public class PersistentSROptions {
// Use this for initialization
public PersistentSROptions ()
{
SROptions.Current.PropertyChanged += OnSROptionsPropertyChanged;
InitializePersistent();
}
//if property is marked [Persistent] and is set, this will save its value to playerprefs
private void OnSROptionsPropertyChanged(object sender, string propertyname)
{
PropertyInfo property = sender.GetType().GetProperty(propertyname);
if(property != null && !Attribute.IsDefined(property, typeof(PersistentAttribute)))
return;
//currently only supports floats. no reason this check cant be expanded. maybe best to use a generic delegate
if (property.PropertyType == typeof(Single))
{
ExternalConfig.SetKey(propertyname, (float)property.GetValue(sender, null));
}
}
//finds all properties marked [Persistent] and loads them from playerprefs if a key is there.
public void InitializePersistent()
{
Type objtype = SROptions.Current.GetType();
foreach (var propertyInfo in objtype.GetProperties())
{
foreach (var customAttribute in propertyInfo.GetCustomAttributes(typeof(PersistentAttribute), false))
{
PersistentAttribute persistent = (PersistentAttribute)customAttribute;
UnityEngine.Debug.Log(propertyInfo.Name + " is marked as persistent");
//currently only supports floats. no reason this check cant be expanded. maybe best to use a generic delegate
if (propertyInfo.PropertyType == typeof(System.Single))
{
if(ExternalConfig.HasKey(propertyInfo.Name))
propertyInfo.SetValue(
SROptions.Current,
(float)ExternalConfig.GetKey(propertyInfo.Name, 0),
null
);
}
}
}
}
}
@pajama
Copy link
Author

pajama commented Nov 27, 2017

make sure to construct the class. I do it in my Zenject installer.

Also add this method to ExternalConfig

public static bool HasKey(string keyName) { JToken keyToken = _configData[keyName]; return keyToken != null; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment