ISerializationCallbackReceiver

作者:追风剑情 发布于:2017-5-24 11:54 分类:Unity3d

用来处理不能被JsonUtility序列化的类,比如Dictionary

using UnityEngine;
using System;
using System.Collections.Generic;

/// <summary>
/// 封装一个可被JsonUtility序列化&反序列化的字典类
/// </summary>
[Serializable]
public class SerializationDictionary : ISerializationCallbackReceiver
{
    public List<int> _keys = new List<int> { 3, 4, 5 };
    public List<string> _values = new List<string> { "I", "Love", "Unity" };

    //Unity doesn't know how to serialize a Dictionary
    public Dictionary<int, string> _myDictionary = new Dictionary<int, string>();

    public string this[int key]{
        get{
            if (!_myDictionary.ContainsKey(key))
                return string.Empty;
            return _myDictionary[key];
        }
        set{
            if (_myDictionary.ContainsKey(key))
                _myDictionary[key] = value;
            else
                _myDictionary.Add(key, value);
        }
    }

    public void OnBeforeSerialize()
    {
        _keys.Clear();
        _values.Clear();

        foreach (var kvp in _myDictionary)
        {
            _keys.Add(kvp.Key);
            _values.Add(kvp.Value);
        }
    }

    public void OnAfterDeserialize()
    {
        _myDictionary = new Dictionary<int, string>();

        for (int i = 0; i != Math.Min(_keys.Count, _values.Count); i++)
            _myDictionary.Add(_keys[i], _values[i]);
    }
}

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号