Search code examples
c#unity-game-engineunity-editor

How to show the following KeyValuePair in the unity editor(so that it is editable)


In a bitesize: I have a KeyValuePair that I want to display and make editable in the Inspector.

I have the following implementing class of my custom Key value pair.

using UnityEngine;
namespace Unit.Properties
{
    public class ClassificationPropertySuperClass : MonoBehaviour, IClassificationUnitProperty
    {
        [SerializeField]
        KeyValuePair<UnitClassifications, float> value;

        public KeyValuePair<UnitClassifications, float> GetComponentValue()
        {
            return value;
        }

        public void SetComponentValue(KeyValuePair<UnitClassifications, float> value)
        {
            this.value = value;
        }
    }
}

And just for information this is the custom KeyValuePair class I made

[System.Serializable]
public class KeyValuePair<TKey, TValue>
{
    public KeyValuePair()
    {
    }

    public KeyValuePair(TKey key, TValue value)
    {
        Key = key;
        Value = value;
    }

    public TKey Key { get; set; }
    public TValue Value { get; set; }
}

Now the core of the issue is that I cannot edit these values in the inspector. For the designers this is an absolute must. I would love to create a editor script too add this functionality but I get kinda lost when it comes to those. Anyone willing to help me out?

Just for reference this is how they appear now in the Inspector

enter image description here

Any help is much appreciated!


Solution

  • The Inspector can't display/edit Properties by default.

    Instead of

    public TKey Key { set; get;}
    public TValue Value { set; get; }
    

    use

    public TKey Key;
    public TValue Value;
    

    It than should be editable in the Inspector.


    In newer versions you also can do

    [field: SerializeField] public TKey Key { set; get;}
    [field: SerializeField] public TValue Value { set; get; }