-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyedCapabilityMachine.cs
More file actions
90 lines (78 loc) · 2.75 KB
/
KeyedCapabilityMachine.cs
File metadata and controls
90 lines (78 loc) · 2.75 KB
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
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
using Exanite.Core.Collections;
using Sirenix.OdinInspector;
using UnityEngine;
namespace CodeName.StateMachines
{
[Serializable]
public class KeyedCapabilityMachine<TKey, TCapability> : CapabilityMachine<TCapability>, ICapabilityMachine<TKey, TCapability>, ISerializationCallbackReceiver where TCapability : class, ICapability
{
[HideInInspector]
[SerializeField] private List<RegisteredCapability> serializedRegisteredCapabilities = new();
[ShowInInspector]
[PropertyOrder(20)]
private TwoWayDictionary<TKey, TCapability> registeredCapabilities = new();
public IReadOnlyTwoWayDictionary<TKey, TCapability> RegisteredCapabilities => registeredCapabilities;
public override void EnableCapability(TCapability capability)
{
if (capability == null)
{
throw new ArgumentNullException(nameof(capability));
}
if (!registeredCapabilities.Inverse.ContainsKey(capability))
{
throw new InvalidOperationException("Capability is not registered");
}
base.EnableCapability(capability);
}
public void OnBeforeSerialize()
{
serializedRegisteredCapabilities.Clear();
foreach (var (key, state) in registeredCapabilities)
{
serializedRegisteredCapabilities.Add(new RegisteredCapability(key, state));
}
}
public void OnAfterDeserialize()
{
registeredCapabilities.Clear();
foreach (var entry in serializedRegisteredCapabilities)
{
try
{
registeredCapabilities.Add(entry.Key, entry.Capability);
}
catch (ArgumentNullException e)
{
Debug.LogError($"Deserialized a null capability with key '{entry.Key}': {e}");
}
catch (Exception e)
{
Debug.LogError(e);
}
}
}
[Serializable]
private struct RegisteredCapability
{
[SerializeField] private TKey key;
[SerializeField] private TCapability capability;
public RegisteredCapability(TKey key, TCapability capability)
{
this.key = key;
this.capability = capability;
}
public TKey Key
{
get => key;
set => key = value;
}
public TCapability Capability
{
get => capability;
set => capability = value;
}
}
}
}