I have a property (called "Head") that can be set externally. When "Head" is not set, it uses Unity3D's MonoBehaviour
functions to try to find the best value for "Head". I started with a nested if
, but the nesting was starting to get out of hand.
if (Head == null)
{
Head = this.GetComponent<Camera>();
if (Head == null)
{
Head = this.GetComponentInChildren<Camera>();
if (Head == null)
{
Head = Camera.main;
}
}
}
So I developed a loop:
System.Func<Camera>[] fallbacks = new System.Func<Camera>[]
{
() => this.GetComponent<Camera>(),
() => this.GetComponentInChildren<Camera>(),
() => Camera.main,
};
foreach (var fallback in fallbacks)
{
if (Head != null)
{
break;
}
Head = fallback();
}
Would this create too much lambda overhead? Do you think the lambdas even increases readability? Is there a more elegant way to handle multiple fallbacks?
Edit:
RobH helped me discover the Null coalescing doesn't work with Unity3D components. RobH's extension method workaround worked great with some tweaking. I had to enforce that comparison had to be done through UnityEngine.Object.
public static T IfNullThen<T>(this T obj, Func<T> factory) where T : UnityEngine.Object
{
return obj != null ? obj : factory();
}
With that extension method my code is now just
Head = Head
.IfNullThen(() => this.GetComponent<Camera>())
.IfNullThen(() => this.GetComponentInChildren<Camera>())
.IfNullThen(() => Camera.main);