Comparing ScriptableObject hierarchy

Hey,

I need a little help wit a comparison.

Goal: I want to have an inheritance tree of CargoTypes and a tank that maybe only stores anything from the tree “CargoType.Liquid”. One maybe only “CargoType.Liquid.Fuel”.

As I only want to write the Storage Class once, I want to be able to drag the possible CargoTypes into a list. But that should always include all items inheriting, in case there is an ew fuel created later on.

Example:

[CreateAssetMenu (fileName="New CargoType", menuName ="SpaceTrader/CargoType/Basic")]
public class CargoType : ScriptableObject
{

    public string cargoName;
    public Sprite cargoIcon;
    public string cargoDescription;
    public float weightPerUnit;

}
[CreateAssetMenu (fileName="New CargoType Liquid", menuName ="SpaceTrader/CargoType/Liquid")]
public class Liquid: CargoType
{

}
[CreateAssetMenu (fileName="New CargoType Fuel", menuName ="SpaceTrader/CargoType/Fuel")]
public class Fuel: Liquid
{

}

On a storage tank I would have a List that would include a CargoType Liquid Scriptable object. Now if the player wants to load CargoType.Liquid.Fuel, how can I compare that while preventing CargoType.Solid from being stored?

Possible solution A
I though about manually keeping the full classname in a variable and then simply comparing these with string.Contains(). But relying on strings feels pretty bad.

Any better ideas?

If I’m reading you right, you could use System.IsAsignableFrom() to determine whether the child classes can be assigned to the specific restriction applied to your storage tank.

Note that the method is kind of backwards. You would use the type of the restriction inside the .IsAsignableFrom() method.

Something like: if (cargoToAdd.GetType().IsAsignableFrom(cargoRestriction.GetType())) if that makes sense.

1 Like