Skip to content

Optional

yenmoc edited this page Jun 26, 2023 · 2 revisions

What

It's really a simple pattern that works in unity

It works like a normal variable but can be toggled on and off in the inspector as a default option

image

Usages

public Optional<string> userName = "Aprius";
public Optional<float> damage = 16.5f;
public Optional<SpriteRenderer> avatar;
public Optional<StringVariable> hp;
using UnityEngine;
  
  public class OptionalDemo : MonoBehaviour
  {
      [Header(" [ Floats ] ")]
      [SerializeField] Optional<float> optionalFloat = 100.95f;


      [Header(" [ Float Ranges ] ")]
      // this won't work as Range attribute check for field Type and theres no way to support custom classes
      [SerializeField][Range(0,500)] Optional<float> optionalRange = 1.5986f;


      [Header(" [ Integers ] ")]
      [SerializeField] Optional<int> optionalInt = 50;
      [SerializeField] Optional<int> optionalInt2;


      [Header(" [ Transforms ] ")]
      [SerializeField] Optional<Transform> optionalTransform = null;
      [SerializeField] Optional<Transform> optionalTransform2 = null;


      private void Start() 
      {
          optionalFloat += 1.1f;

          if (optionalInt == optionalInt2) Debug.Log("optionalInt == optionalInt2");

          if (optionalTransform == optionalTransform2) Debug.Log("optionalTransform == optionalTransform2");

          if (optionalTransform == null) Debug.Log("optionalTransform is null");
          else optionalTransform = null;

          if (optionalInt == null) Debug.Log("optionalInt can't be null. Something is wrong!");
          
          if (optionalInt) Debug.Log("optionalInt is enabled.");
          
          // optionalFloat = optionalTransform;
      }
  }
Clone this wiki locally