So I posted asking if I could use the ?? operator to achieve this, but @BenZed figured out a different way using an extension method and an anonymous delegate, but that required the “this” keyword… which annoyed me even in my sleep. So, I figured why not just make it a protected method. I can’t stop thinking about how awesome this is going to make programming my next game.
Basically what I wanted was the ability to create a code block that references the component internally, then forgets about the reference when it is finished without the need to declare a new variable or check for nulls. And this is it!!!
Here’s an example of using it:
using UnityEngine;
public class TurnRed : MonoX {
void Start () {
With<Renderer> ((component) => {
component.material.color = Color.red;
});
}
}
Here’s the base class:
using UnityEngine;
using System;
public class MonoX : MonoBehaviour {
protected void With<T>(Action<T> action) where T : Component {
var component = GetComponent<T>();
if (component) {
action(component);
} else {
Debug.Log("Component " + typeof(T).ToString() + " not found on " + this.name);
}
}
}
It might be a little shaky if someone didn’t get/doesn’t like the whole lambda thing, but the naming convention makes it so that anybody could use this abstraction easily, even copy and paste the first line and just change the names. The mind says, “Oh, if I just change the names this will work with any component.” And it will. And you can do whatever you want in the space. So, it’s honest. I think this is very nice.
It fails without blowing up your code with a rogue null reference exception, but mentions that there’s an issue…
