Unity CustomEditor for generic serialized type?

I’ve got a generic, serialized class type in Unity that I’m trying to write a CustomEditor for. I’m running into trouble with var myScript = target as <MyClass>, where it won’t cast it to my (generic) class type:

[Serializable]
public class EnemyStatsAttack {
  public float attackDistance = 10f;
  //etc
}

[CustomEditor(typeof(EnemyStatsAttack))]
public class EnemyStatsComponentEditor : Editor {
  override public void OnInspectorGUI() {
    var myScript = target as EnemyStatsAttack; //error: UnityEngine.Object cannot be cast to EnemyStatsAttack
  }
}

I’ve tried deriving EnemyStatsAttack from UnityEngine.Object, however then in the inspector the class isn’t serialized and I can’t set the fields (it just shows None (Enemy Stats Attack) in the box).

How do I fix this?

That doesn’t work. You’re looking for a PropertyDrawer, not a CustomEditor. Editors are for handling standalone serialized objects. Unity can only serialize objects derived from UnityEngine.Object and the only classes you can extend are MonoBehaviour and ScriptableObject. Any “normal” custom serializable class is just serialized along / inline with the “root” asset. So you need a PropertyDrawer for your serializable class / struct.

Note that you said “generic” class. I guess you did not mean a C# class with generic type parameters but just a “versatile” class, right?