コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】どんな型でも簡単に保存と読み込みができるPlayerPrefsの関数を定義する

概要

Unity 5.3 から追加された「UnityEngine.JsonUtility」と
「UnityEngine.PlayerPrefs」を組み合わせることで
どんな型でも簡単に保存と読み込みができる
PlayerPrefsの関数を定義することができます

using UnityEngine;

public static class PlayerPrefsUtils
{
    /// <summary>
    /// 指定されたオブジェクトの情報を保存します
    /// </summary>
    public static void SetObject<T>( string key, T obj )
    {
        var json = JsonUtility.ToJson( obj );
        PlayerPrefs.SetString( key, json );
    }
    
    /// <summary>
    /// 指定されたオブジェクトの情報を読み込みます
    /// </summary>
    public static T GetObject<T>( string key )
    {
        var json = PlayerPrefs.GetString( key );
        var obj = JsonUtility.FromJson<T>( json );
        return obj;
    }
}
[Serializable]
class Character
{
    public int Id;
    public string Name;
    public int[] SkillIdList;
}

void Start ()
{
    var key = "hoge";
    var chara = new Character
    {
        Id = 25, 
        Name = "ピカチュウ", 
        SkillIdList = new []{ 1, 2, 3, 4 }, 
    };
    
    PlayerPrefsUtils.SetObject( key, chara );
    var result = PlayerPrefsUtils.GetObject<Character>( key );
}