字典在Inspector的显示
《unity3D游戏开发第二版》记录 在编辑面板中可以利用序列化监听接口特性对字典进行序列化。 主要继承ISerializationCallbackReceiver接口 实现OnAfterDeserialize() OnBeforeSerialize()的方法进行监听序列化和反序列化之前的事件。
public class SerializeTest :MonoBehaviour,ISerializationCallbackReceiver
{
[SerializeField]
private List<Sprite> mValues=new List<Sprite>();
[SerializeField]
private List<string> mKeys=new List<string>();
public Dictionary<string,Sprite> mSpriteDic=new Dictionary<string, Sprite>(5);
public void OnAfterDeserialize()
{
mSpriteDic.Clear();
if(mKeys.Count!=mValues.Count) Debug.Log("键和值不对应");
else
{
for(int i=0;i<mValues.Count;++i)
{
mSpriteDic.Add(mKeys[i],mValues[i]);
}
}
}
public void OnBeforeSerialize()
{
mKeys.Clear();
mValues.Clear();
foreach(var pair in mSpriteDic)
{
mKeys.Add(pair.Key);
mValues.Add(pair.Value);
}
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(SerializeTest))]
public class ScriptInspector:Editor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
SerializedProperty propertyKey=serializedObject.FindProperty("mKeys");
SerializedProperty propertyValue=serializedObject.FindProperty("mValues");
int size=propertyKey.arraySize;
GUILayout.BeginVertical();
for(int i=0;i<size;i++)
{
GUILayout.BeginHorizontal();
SerializedProperty key=propertyKey.GetArrayElementAtIndex(i);
SerializedProperty value=propertyValue.GetArrayElementAtIndex(i);
key.stringValue=EditorGUILayout.TextField("key",key.stringValue);
value.objectReferenceValue=EditorGUILayout.ObjectField("value",
value.objectReferenceValue,typeof(Sprite),false);
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
GUILayout.BeginHorizontal();
if(GUILayout.Button("+"))
{
(target as SerializeTest).mSpriteDic[size.ToString()]=null;
}
GUILayout.EndHorizontal();
serializedObject.ApplyModifiedProperties();
}
}
#endif
|