-
Notifications
You must be signed in to change notification settings - Fork 0
/
SaveableEntity.cs
79 lines (66 loc) · 2.38 KB
/
SaveableEntity.cs
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
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[ExecuteAlways]
public class SaveableEntity : MonoBehaviour
{
[SerializeField] string uniqueIdentifier = "";
static Dictionary<string, SaveableEntity> globalLookup = new Dictionary<string, SaveableEntity>();
public string GetUniqueIdentifier()
{
return uniqueIdentifier;
}
public object CaptureState()
{
Dictionary<string, object> state = new Dictionary<string, object>();
foreach (ISaveable saveable in GetComponents<ISaveable>())
{
state[saveable.GetType().ToString()] = saveable.CaptureState();
}
return state;
}
public void RestoreState(object state)
{
Dictionary<string, object> stateDict = (Dictionary<string, object>)state;
foreach (ISaveable saveable in GetComponents<ISaveable>())
{
string typeString = saveable.GetType().ToString();
if (stateDict.ContainsKey(typeString))
{
saveable.RestoreState(stateDict[typeString]);
}
}
}
#if UNITY_EDITOR
private void Update()
{
if (Application.IsPlaying(gameObject)) return; //Epitrepei na trexei mono sto edit
if (string.IsNullOrEmpty(gameObject.scene.path)) return; // me ayto dn trexei o kwdikas sta prefabs.. nice tric Yo!!
SerializedObject serializedObject = new SerializedObject(this);
SerializedProperty property = serializedObject.FindProperty("uniqueIdentifier");
if (string.IsNullOrEmpty(property.stringValue) || !IsUnique(property.stringValue))
{
property.stringValue = System.Guid.NewGuid().ToString();
serializedObject.ApplyModifiedProperties();
}
globalLookup[property.stringValue] = this;
}
#endif
private bool IsUnique(string candidate)
{
if (!globalLookup.ContainsKey(candidate)) return true;
if (globalLookup[candidate] == this) return true;
if (globalLookup[candidate] == null)
{
globalLookup.Remove(candidate);
return true;
}
if (globalLookup[candidate].GetUniqueIdentifier() != candidate)
{
globalLookup.Remove(candidate);
return true;
}
return false;
}
}