- Home /
Question by
danieltranca · Nov 04, 2015 at 06:53 PM ·
serializationcustom editorgenerics
I need a dictionary for a custom inspector
So I need a dictionary structure to save things in a custom editor. I know that dictionaries are not allowed so I tried to create my own type, finding out that neither generics are allowed. But List is. So starting from this I have created a class that extends the List and add a small functionality that allows me to treat this object as a Dictionary. Here's the code:
public class CustomDictionary : List<CustomDictionaryItem>
{
public void Add (string key, UnityEngine.Object value)
{
this.Add (new CustomDictionaryItem (key, value));
}
public bool ContainsKey (string key)
{
return this.Any (sdi => sdi.Key == key);
}
public bool Remove (string key)
{
return this.RemoveAll (sdi => sdi.Key == key) != 0;
}
public UnityEngine.Object this [string key] {
get {
if (ContainsKey (key))
return (UnityEngine.Object)this.First (sdi => sdi.Key == key).Value;
return null;
}
set {
if (ContainsKey (key)) {
CustomDictionaryItem item = this.First (sdi => sdi.Key == key);
item.Value = value;
} else
Add (key, value);
}
}
public List<string> Keys {
get {
return this.Select (sdi => sdi.Key).ToList ();
}
}
public List<UnityEngine.Object> Values {
get {
return this.Select (sdi => (UnityEngine.Object)sdi.Value).ToList ();
}
}
}
[Serializable]
public class CustomDictionaryItem
{
[SerializeField]
private string m_key;
public string Key{ get { return m_key; } set { m_key = value; } }
[SerializeField]
private UnityEngine.Object m_value;
public UnityEngine.Object Value{ get { return m_value; } set { m_value = value; } }
public CustomDictionaryItem (string key, UnityEngine.Object value)
{
m_key = key;
m_value = value;
}
}
I would like it to be typed to be honest(instead of UnityEngine.Object) but I tried to remove the generics in hope that it would work. It doesn't. The values are not saved after the game is started.
PS: this "public List m_customDictionary;" works ok, as it should, but does not have the functionality that I want. Any ideas? Thank you!
Comment