Community Made Tools

Have you made any useful utilities with Odin?

Login and submit your creations here


Authored by Lucas
Shared 04-09-2022

Hi, I started using Odin Validator recently and one of the features that really interest me is the 'reference required by default'. This completely avoids bug that could occur when forgetting to assign something.

Having every reference required is of course not very practical, that's why the 'Optional' attribute exists. This attribute works fine but doesn't explicitly convey to the user that the variable is opional when using it in code.

That's why I created UnityOption type. It conveys that the field is optional, and requires the user to take into account that the value could be missing. Significantly reducing potential runtime erros.


public class Example : MonoBehaviour
   [SerializeField] private UnityOption<GameObject> _optionalGameObject;
   [SerializeField] private UnityOption<string> _optionalString;
   [SerializeField] private UnityOption<int> _optionalInt;

   private void Awake() {
      GameObject go = optional.Match( 
            Some: _optionalGameObject  => _optionalGameObject,
            None: () => //return another GameObject, null, or throw an error.

      // Returns the Some case 'as is' and 10 in the None case
      int x = _optionalInt.IfNone(10);        

      // As above, but invokes a Func<T> to return a valid value for x
      _optionalString s = optional.IfNone(() => GetAlternativeString());        
      // Invokes an Action<T> if in the Some state.
      _optionalString.IfSome(v => Debug.Log(v));

This also works with the 'No empty strings' rule.

For more info and how to install, check out the GitHub page: