56 lines
1.7 KiB
C#
56 lines
1.7 KiB
C#
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
using System;
|
|
|
|
// Serialize対象が自作classなら[Serializable]を付ける必要がある
|
|
|
|
// List<T> -> Json文字列 ( 例 : List<Enemy> )
|
|
// string str = JsonUtility.ToJson(new Serialization<Enemy>(enemies));
|
|
// Json文字列 -> List<T>
|
|
// List<Enemy> enemies = JsonUtility.FromJson<Serialization<Enemy>>(str).ToList();
|
|
[Serializable]
|
|
public class Serialization<T> {
|
|
[SerializeField]
|
|
private List<T> target;
|
|
public List<T> ToList(){
|
|
return target;
|
|
}
|
|
|
|
public Serialization(List<T> target){
|
|
this.target = target;
|
|
}
|
|
}
|
|
|
|
// Dictionary<TKey,TValue> -> Json文字列 ( 例 : Dictionary<int, Enemy> )
|
|
// string str = JsonUtility.ToJson(new Serialization<int, Enemy>(enemies));
|
|
// Json文字列 -> Dictionary<TKey,TValue>
|
|
// Dictionary<int, Enemy> enemies = JsonUtility.FromJson<Serialization<int, Enemy>>(str).ToDictionary();
|
|
[Serializable]
|
|
public class Serialization<TKey, TValue> : ISerializationCallbackReceiver {
|
|
[SerializeField]
|
|
private List<TKey> keys;
|
|
[SerializeField]
|
|
private List<TValue> values;
|
|
|
|
private Dictionary<TKey, TValue> target;
|
|
public Dictionary<TKey, TValue> ToDictionary(){
|
|
return target;
|
|
}
|
|
|
|
public Serialization(Dictionary<TKey, TValue> target){
|
|
this.target = target;
|
|
}
|
|
|
|
public void OnBeforeSerialize(){
|
|
keys = new List<TKey>(target.Keys);
|
|
values = new List<TValue>(target.Values);
|
|
}
|
|
|
|
public void OnAfterDeserialize(){
|
|
var count = Math.Min(keys.Count, values.Count);
|
|
target = new Dictionary<TKey, TValue>(count);
|
|
for(var i = 0; i < count; ++i){
|
|
target.Add(keys[i], values[i]);
|
|
}
|
|
}
|
|
} |