A Unity3D pattern I've not seen discussed

Here’s a design pattern I use a lot in Unity when sketching out or testing behaviours:

public bool bangFollow;

void Update () {
	if (bangFollow)
	{
		bangFollow = false;
		FollowSpline();
	}
}

As I use it a bunch, I’m not sure how clear the intent here is to other people. The idea is that you want to test a bit of behaviour before you’ve necessarily got the hooks in place to call it at the right time (or you want to test a bit of behaviour in isolation). It’d be great to be able to just type into an interpreter “testCreature.FollowSpline();”, but we don’t have an interpreter handy (and if we did, we would have to get the reference to the GameObject first, when it’s right there in the Inspector…). So instead we make a boolean visible in the Inspector, and use it entirely for communicating to the script that it should run a function. And then to prevent it from happening more than the once, we set it false.

(Why “bang”? Because I’ve played around with pd, which has a similar concept of a button you can press to send a signal/invoke a function interactively)

[Edit] @jonbro prompted another thought: Why not just use GetKeyDown? The answer is: because this way you can have a whole army of the same behaviour active, and only trigger a single one of them.

I once got messy trying to write an editor script that used reflection and a custom attribute to achieve this in a more convoluted way, but it was a bit of a mess, and I didn’t know if anyone else felt the need for it.

The other thing I do is create variables in the Inspector that are purely used to show state to me while debugging – I should really come up with come kind of hungarian notation to mark these off. I guess “debugWhatever” would cover it?


Wed Mar 20, 2013