Option to replace Nullable as in functional programming for Unity.
add "com.corby.option": "https://github.com/CorbyO/Option.git"
to Packages/manifest.json
.
openupm add com.corby.option
Option<int> num = new(); // None<int>
Option<int> num = 3.ToSome(); // Some<>(3)
Option<Transform> parent = transform.parent.ToOption(); // Some<> or None
public static Option<Transform> GetParent<T>(this Transform transform)
{
return transform.parent.ToOption();
}
var parentName = transform.GetParent().Unwrap() switch
{
Some<Transform> parent => parent.name,
None<Transform> => "None"
};
This is a simple example of how to serialize a class or struct that contains Option.
[Serializable]
public struct TestStruct
{
public Option<int> Number;
public Option<string> Name;
public Option<Vector3> Position;
}
[Serializable]
public class TestClass
{
public Option<Sprite> Sprite;
public Option<List<int>> Numbers;
}
public class TestComponent : MonoBehaviour
{
public Option<TestStruct> Struct;
public Option<TestClass> Class;
}