Asking about another way to avoid expected null values

So in general I tend to not trust user input or input to public methods when I write my code. I tend to check for out of bounds, for null values, etc and try to handle these cases. [I’m not an engineer, but it’s a habit I picked up from 20+ years of listening to engineers work] Here is what my code looked like before this lesson. So the good news is I would have caught this problem early. The bad news is my code has no graceful fallback and it would have been awesome to find this mistake before running the code.

Here’s my question: This lesson helped us solve this instance but I am wondering if there’s some generalizable lesson here? We learned a tiny bit about editor scripts earlier in this course. Are editor scripts a good way to check if you’ve configured something stupidly with your editor references?

Related: I’m thinking of giving all my weapons a “weaponType” enum and making sure that for a given weaponType (e.g. unarmed melee, unarmed magic, melee weapon, ranged weapon, magic staff, etc) that all appropriate fields are set for that type. For example it would be AMAZING if the inspector tab could tell me that some object or component is not set up properly.

if (animatorOverride != null)
            {
                animator.runtimeAnimatorController = animatorOverride;
            }
            else
            {
                if (name != "Unarmed")
                {
                    Debug.LogError($"Attempting to spawn a weapon called {name} with no animator override!");
                }
            }

Did a bit of digging an it looks like there is an OnValidate() method.

Ok - now I’m curious if I can use it to trigger a message to show right within inspector (e.g. “you haven’t set an animator override!”) and/or block successful compilation until the error is fixed.

Since serialized values in the Editor are not really “compiled”, the best you can do is to put that Debug in OnValidate itself. OnValidate can also reject values that don’t make sense… For example, in WeaponConfig.cs, you could have an OnValidate that did this:

void OnValidate()
{
    if(animatorOverride==null && name!="Unarmed")
    {
        Debug.LogWarning("Weapon {name} is not Unarmed, but does not have an animator override assigned");
     }
}

Ultimately, editor code is the best way to ensure things are filled out correctly, or at least to show the user that there are still mandatory fields that need to be fixed before the item will work correctly. Editor scripting is an advanced topic, and if you look at some of the topics in BriansTipsAndTricks, you’ll see some examples of Editor code in action.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms