summaryrefslogtreecommitdiff
path: root/Client/Assets/Scripts/XEditor/XSkillEditor/XSerialized.cs
blob: 6d71a0bc5751c9a4bf21e36974d5b4cf4152029e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using UnityEngine;

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace XEditor
{
    public class XSerialized<T> where T : class
    {
        //deep copy of T
        private static string SerializeToString(T value)
        {
            using (MemoryStream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, value);
                objectStream.Flush();
                return Convert.ToBase64String(objectStream.ToArray());
            }
        }

        private static T DeserializeFromString(string data)
        {
            byte[] bytes = Convert.FromBase64String(data);
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                return (T)(new BinaryFormatter()).Deserialize(stream);
            }
        }

        [SerializeField]
        private string _serializedData;

        protected T _class;

        public XSerialized() { }

        public XSerialized(T _class)
        {
            Set(_class);
        }

        public void Set(T _class)
        {
            this._class = _class;
            Serialize();
        }

        public T Get()
        {
            if (_class == null) _class = Deserialize();
            return _class;
        }

        public virtual void Serialize()
        {
            _serializedData = SerializeToString(_class);
        }

        protected virtual T Deserialize()
        {
            return DeserializeFromString(_serializedData);
        }
    }
}
#endif