更新日期:2025年3月26日。
Github 倉庫:https://github.com/SaiTingHu/HTFramework
Gitee 倉庫:https://gitee.com/SaiTingHu/HTFramework
索引
- 一、SerializableDictionary可序列化字典
- 1.使用SerializableDictionary
- 2.實現思路
- 二、SerializableHashSet可序列化哈希集
- 1.使用SerializableHashSet
- 2.實現思路
一、SerializableDictionary可序列化字典
SerializableDictionary<,>可序列化字典
類型支持序列化(用于替代不可序列化的Dictionary<,>
類型),其擁有與Dictionary<,>
一樣的適用于頻繁查找、插入和刪除數據
的性能優勢。
1.使用SerializableDictionary
使用SerializableDictionary很簡單,直接定義SerializableDictionary的可序列化字段即可:
public class Test : HTBehaviour
{[Label("簡單字典示例")] public SerializableDictionary<string, string> d1;[Label("復雜字典示例")] public SerializableDictionary<string, Data> d2;protected override void Awake(){base.Awake();foreach (var item in d1){Debug.Log($"簡單字典示例中元素:{item.Key} - {item.Value}");}foreach (var item in d2){Debug.Log($"復雜字典示例中元素:{item.Key} - {item.Value}");}}[Serializable]public class Data{public string Name;public int Age;public Vector2 Pos;public Vector3 Angle;public Material Cloth;}
}
在檢視器面板是可序列化的(同時支持為其附加各種Inspector特性):
Tips:為了降低各
鍵值對(Key-Value)
之間的視覺干擾,只有選中的鍵值對(Key-Value)
呈現為亮色,其他的顯示為暗色。
運行場景:
2.實現思路
實現思路其實很簡單,SerializableDictionary中維護了兩個List用于序列化鍵值對(Key-Value)
,然后在運行時動態構建一個Dictionary
。
二、SerializableHashSet可序列化哈希集
SerializableHashSet<>可序列化哈希集
類型支持序列化(用于替代不可序列化的HashSet<>
類型),其擁有與HashSet<>
一樣的適用于頻繁查找、插入和刪除數據
的性能優勢。
1.使用SerializableHashSet
使用SerializableHashSet很簡單,直接定義SerializableHashSet的可序列化字段即可:
public class Test : HTBehaviour
{[Label("簡單哈希集示例")] public SerializableHashSet<string> s1;[Label("復雜哈希集示例")] public SerializableHashSet<Data> s2;protected override void Awake(){base.Awake();foreach (var item in s1){Debug.Log($"簡單哈希集示例中元素:{item}");}foreach (var item in s2){Debug.Log($"復雜哈希集示例中元素:{item}");}}[Serializable]public class Data{public string Name;public int Age;public Vector2 Pos;public Vector3 Angle;public Material Cloth;}
}
在檢視器面板是可序列化的(同時支持為其附加各種Inspector特性):
運行場景:
2.實現思路
實現思路其實很簡單,SerializableHashSet中維護了一個List用于序列化,然后在運行時動態構建一個HashSet
。