Display Scriptable object in inspector using generic/template variables

Hi there,

I’m struggling to display a generic variable in the inspector using the scriptable objects
Here’s what my code look like

[System.Serializable]
public class VariableTypes<T> : ScriptableObject
{
    [SerializeField]
    public T Value;

    public virtual T GetValue() { return Value; }
}

[System.Serializable]
[CreateAssetMenu(menuName = "SOExtention/Variables/Int")]
public class VariableInt : VariableTypes<int> { }
[System.Serializable]
public abstract class VariableReferenceTypes<T1>
{
    public bool UseConstant = true;

    [SerializeField]
    public T1 ConstantValue;

    [SerializeField]
    public VariableTypes<T1> Variable;

    public T1 Value
    {
        get { return UseConstant ? ConstantValue : Variable.GetValue(); }
    }
}

[Serializable] 
public class VariableReferenceInt : VariableReferenceTypes<int> { }

But here’s what the final result look like

The test string is what is supposed to display, and the String Type is my result using the generic

6093738--662127--upload_2020-7-15_13-47-4.png

Did someone already faced this issue ?

Any help would be appreciated

I’m not sure there’s a true generic mapper that would work, and you might have to query the type and write your own custom field editor. I think this might be your friend for such an endeavor:

But I am speculating on that last bit so if someone knows that is NOT it, please tell me and I will edit this post.

Unfortunately i tried that with the editor but doesn’t show up

[CustomEditor(typeof(VariableReferenceString))]
[CanEditMultipleObjects]
public class VariableTypeCustomEditor : Editor
{
     SerializedProperty m_GameObjectProp;

    void OnEnable()
    {
        // Fetch the objects from the GameObject script to display in the inspector
        m_GameObjectProp = serializedObject.FindProperty("Variable");
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        //The variables and GameObject from the MyGameObject script are displayed in the Inspector with appropriate labels
        EditorGUILayout.PropertyField(m_GameObjectProp, new GUIContent("Game Object"));

        // Apply changes to the serializedProperty - always do this at the end of OnInspectorGUI.
        serializedObject.ApplyModifiedProperties();
    }
}

I think that the only way left for me is to do all that manually without using generics variable which is quite annoying but… i don’t think i have other choices

I’m afraid you have to use concrete(non-generic) class at this point
public VariableTypes<T1> Variable;
like
public VariableInt Variable;
but this will ruin the whole point of the generic class.
Unity 2020 support this even without concreting generic class, so you don’t need VariableReferenceInt and can do right away
public VariableReferenceTypes<int> myInt;

1 Like