Is there some way to make a property return a static value if the object is null/does not exist?

Hello,

can I make a property of an object return a static value if the object itself is null? I’m trying to use a component system for some of my game objects and I figured it’d be convenient if the property just returned the value 0 if the object didn’t exist (if my spaceship didn’t have a booster, I don’t want to check for missing boosters all the time) It’d be far more convenient if booster power requests just returned 0.
My current attempt at coding this looked like this, but it returns null reference errors if I actually try to access the properties.

private bool initialised = false;
    [SerializeField, Tooltip("maximum boosting Time for BoosterDrive ScriptableObject"), Range(0f,1000f)] private float maxBoost = 100f;
    public float MaxBoost
    {
        get
        {
            if(this == null)
            {
                return 0f;
            }
            else return maxBoost;
        }
    }

Honestly no clue if this is even possible, but it’d be very neat if it was.

If this is null then you can’t access properties on an object because its a null pointer i.e. it doesn’t have a type of your object so it doesnt have the properties of your object either.


i.e. you cant use instance members if you dont have an instance to reference.

I believe you can use Null Conditional Operators and Null coalesciong operators to accomplish this. Something like

public static float GetMaxBoost(BoosterDrive boost)
     {
         return boost?.maxDrive ?? 0f;
     }

Which basically checks if boost in null before it tries to access its property, and if it is null then it returns 0 instead. I haven’t really used these myself and I haven’t tested this code so I’m not sure if it works.