Get Type, Cast as and subclasses... HELP !

Hi guys !

I’m setting up my inventory system and I need to call a certain method depending on the type of my item class.
Well, obviously you would think of a Get Type check, but here is the thing :

  • I’m getting a reference of my currently selected object in a VARIABLE of type BaseItem (which is my base class for all my items/weapons/equips…) so the same variable can manage all the subclasses.

Because of this settings, when I try to check what is the Type of my currently selected object, Get Type can’t return any of my subclasses cause they are “stored” as a BaseItem.

At least, that’s how I understand my problem…

What solution do I have ? Setting up an Enum (item-weapon-whatever) in my BaseItem class ?I suppose that would do the job but I’d like to get around this sort of “type-cast” issue !

Thank you all for your input :slight_smile:

GetType will return the type of the instance and not the type of the variable that’s holding it.

However, unless your base class derives from ScriptableObject or MonoBehaviour, Unity serializes fields by their field type and not the type of the instance it’s holding. So it could be that all of your items are getting serialized as BaseItems.

It is explained in this article. Look for “No support for polymorphism”.
https://blogs.unity3d.com/2014/06/24/serialization-in-unity/

1 Like

Actually, my BaseItem DOES derive from MonoBehaviour… :confused:

Normally this indicates a structural problem. You should generally put shared functionality on the base class.

However if you do need it, there are several approaches.

  • Use is to check if a given instance implements a certain runtime type. Cast as appropriate.
  • Use safe casting with as, then check if the result is null
  • Use reflection to get super tricksy
1 Like