Search Unity

Resolved Hide properties from parent class in child class in the inspector

Discussion in 'Scripting' started by VileGoo, May 11, 2020.

  1. VileGoo

    VileGoo

    Joined:
    Apr 29, 2017
    Posts:
    220
    I recently started using overriding after finding out how useful it can be. I've got that all down and it functionally works in my game how I want it to. The problem I'm having now is all the clutter in my inspector, all of the exposed properties from the parent class are also being shown on the child class, I don't want this. I'll try and make an example of what I mean:

    Code (CSharp):
    1. public class Unit : MonoBehaviour
    2. {
    3.     public int health; // <- this should only be visible on this script in the inspector
    4.  
    5.     public virtual void Kill()
    6.     {
    7.         Destroy(this.gameObject);
    8.     }
    9. }

    Code (CSharp):
    1. public class Enemy : Unit
    2. {
    3.     public override void Kill()
    4.     {
    5.         Debug.log("Death");
    6.         base.Kill()
    7.     }
    8. }
    Is what I want possible? I thought using custom inspector scripts would be the way to go, but it just seems unintuitive to make an entire script just to hide a few properties for every child class script, unless I'm not understanding it properly.
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    The only way I know of to do this is to use a custom editor. There isn't an easier way to do it because this is an unusual thing to do. (e.g. usually you'd want to be able to see and edit how much health an enemy has.)

    Note that it might be easier to make the field hidden by default and use a custom inspector for the base class to reveal it, rather than making a custom inspector for every subclass that hides it.


    Alternately, you may be able to restructure your code so that the problem doesn't arise in the first place. Rather than being a subclass of Unit, maybe Enemy should have a Unit as a member? Or use RequireComponent to demand that the attached GameObject also have a Unit as a separate component? Or maybe Unit should be an interface rather than a class?