Custom Editor for base C# class

I seem to come across various answers about not been able to do this without some serious work-arounds but all the posts I came across weren’t exactly for the same reasons I’m looking for.
I have a class to hold info on a slot in a container.

[System.Serializable]
public class ContainerSlot
{
    public ItemObject item;                 //SO item
    public int amount;                      //Says it all
    public ContainerBase parent;            //Parent container
    public int inventoryIndex;              //Current inventory Index 

    public ContainerStorage container;      //Optional container contents class
   


    public ContainerSlot(ItemObject _item, int _amount, int _index)
    {
        item = _item;
        amount = _amount;
        inventoryIndex = _index;

    }

    public void AddAmount(int _value)
    {
        amount += _value;
    }

    public void RemoveAmount(int _value)
    {
        amount -= _value;


    }

}

I’m trying to figure out a way to get the inspector window to only show the “container” field if the “item” field fits a certain rule (the SO item can fit into a certain catagory. I.E item.type == itemType.Storage)

Thanks in advance.

The general answer here is write a custom property drawer for your class:

The easy answer though is to use an off-the-shelf tool like NaughtyAttributes:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html

5 Likes

So this is a class and not a component so you’re going to be using a PropertyDrawer rather than an Editor.

So create a custom propertydrawer:

[CustomPropertyDrawer(typeof(ContainerSlot))]
class ContainerSlotPropertyDrawer : PropertyDrawer

If you’re inheriting from ContainerSlot and want to reuse this property drawer for it, add the ‘true’ flag to the attribute:

CustomPropertyDrawer(typeof(ContainerSlot), true)]

Now from here you have 2 approaches. There is the legacy approach of using the ‘OnGUI’ or the newer approach of ‘CreatePropertyGUI’. Check out the documentation for both:

But effectively in your approach you pick you’ll only draw the elements that meet your conditions. You’re going to read the item field and if it meets your conditions draw the container field.

Note you should probably be checking the SerializedProperty’s SerializedObject field to see if it is drawing multiple objects or not. Since if it is, then there are technically multiple 'item’s. And you may want to behave differently (as in, don’t draw at all).

2 Likes

Many thanks. I’ll give them a read

Great thanks.

Now I just have to get rid of my stacking serielized fields past 10 since I seem to be self referencing slot in container over and over. Ah the love of creating problems for ourselves :smile: