I want to use an interface but the editor doesn't show public properties. What should I do ?

Hello everyone. I’m making a game and I want the player to be able to pick up and carry many different kinds of items in his or her inventory. Please mind that although I have some programming experience, I’ve never made a game before.

So coming from a C# OOP background I thought of creating an interface “IItem” and different classes that inherit it like “Weapon”, “Food” etc.
I want some code to be able to work on an item no matter the type of item it is.

The problem is that interfaces doesn’t take variables in their definitions but properties, and the editor does the exact opposite and doesn’t show properties but variables. And I need to be able to fill in the details of each different item for each instance of it.

So, does anybody know of a workaround ?

Could you use Inheritance?

Like @Nyro suggested, you can use an Abstract class.

Although, you can also use GetComponent<yourInterface>() or any of the GetComponent methods.

You may also want to have a look at ScriptableObject.

By the way, these are topics I touch on in my SOLID design course, available here.

Hi.

Interfaces are Abstract classes are almost the same, but different in two very distinct ways.

Interfaces are just a contract which defines what MUST be implemented by you class in order for it to be that class.

Abstract classes cannot be constructed but provide default functionality or stub methods that your class can inherit from.

For any game object you want to display in the inspector which derives from the abstract class you can just use the abstract class type in place of your specific implementation, the same way interfaces work.

Interfaces don’t play nice in unity because they cannot be serialized. I would suggest creating an abstract base class that also derives from Monobehaviour or ScriptableObject plus any interface you decide to implement. Then you’ll have the best of both worlds.