ScriptableObjects get interface method

Hi, I am making a game and in this game I want to remove from inventory an item which has a durability null (is broken). What I have in mind is when the OnDurabilityNull Action of the item is call, unequip it (if it is an equipement) and remove it from the inventory.

I have some items (Item, shield, usables, spells, armors and weapons) which are scriptableObjects. They all inherit from Item class but some items have the IDurability interface like armors or weapons.

As we can’t GetComponent of a scriptableObjects, I try to cast the item into an interface like that:

IDurability interfaceDurability = (IDurability) item;

if the item is an armor or an weapon, no error but if it is not, an error appears to say “cast is not possible”.

There is a way to do that ?

I thought to a generic method in item class to return :

public T Get<T>() where T : interface
{
    try
    {
        return (T)this;
    }
    catch (Exception)
    {
        return null;
    }
}

But It doesn’t work since we can not use this syntaxe where T : interface.

You want to use this type casting syntax:

if (yourItem is IDurability itemDurability)
{
    //your code here
}

to check if the object implements the IDurability interface and use the output ‘itemDurability’ variable to get what you need off of it.

Thank you so much !!!

I used this code:

public T Get<T>()
{
    if (this is T interfaceType)
        return interfaceType;
    return default(T);
}

And it works perfectly.

I didn’t know that was possible to put a variable at this place.