Delegates, events, lambdas and all things callbacky! (Part 2)

Part two of my delegatey thing begins with lambdas, as promised.

Lambdas are basically a shorter form of anonymous functions than the delegate keyword version.

A few quick examples:

x=>Debug.Log(x);
()=>Debug.Log("Something happened!");
(x, y) => x * y;
x=>{ Debug.Log(x); return x*2; }

The first one takes one parameter and calls Debug.Log on it. You would use this with Action.

The second takes no parameters and calls Debug.Log. For this, simply Action.

The third one takes two parameters and returns the result of the multiplication of the two. This one is Func, e.g. Func.

The last one takes in a single parameter and does two things to it, first printing it with Debug.Log, then returning the value doubled. When using parentheses with lambdas, if the delegate expects a returned value, the return is no longer implicit.

Now, a quick example using lambdas to do something. This time, I’ll show how to inject logic into a function using them:

void Start()
{
	int[] array = new int[]{0,1,2,3,4,5,6,7,8,9};
	DoStuffToAll(array, i => Debug.Log(i.ToString()));
}

void DoStuffToAll(int[] array, Action<int> action)
{
	foreach(int i in array)
	{
		action(i);
	}
}

This code basically loops through all items in the array and performs the action on each, in this case Debug.Log, printing out the values from 0 to 9. As usual, this snippet isn’t terribly useful, as it’s basically the same as a foreach in Start, but the ideas will translate to much more difficult problems.

To expand on it, you could make it do multiple things in one go. What I haven’t yet mentioned about lambdas is that you can encapsulate local variables in them, which means you can do some fairly cool things. This next example does just that, using the same DoStuffToAll from above:

void Start()
{
	int[] array = new int[]{0,1,2,3,4,5,6,7,8,9};
	int total = 0;
	DoStuffToAll(array, i => { Debug.Log(i.ToString()); total += i; });
	Debug.Log("Total is: " + total);
}

This encapsulates an alias (Think along the lines of a reference) to the total variable and increments it by each value in the array. This also works for variables in classes, or anything else you want, but be careful with it, it’s fairly easy to trip up and do something you’re not expecting!

So, now that we’re fairly familiar with lambdas and injecting functionality into other functions, let’s look at events.

Events are similar to properties, but work with delegates. They stop the delegate from being modified or called from outside the instance of the class it belongs to. This ties back into my post about sane data encapsulation. You don’t want other classes to be able to do otherClass.yourDelegate = null, as that could potentially have breaking changes, but you do want to have the option of adding or removing from the delegate.

To show this in action, here is a small example:

void Start()
{
	MyEventTest test = new MyEventTest();
	test.Completed += ()=>Debug.Log("Completed!");
	test.DoSomething();
}

public class MyEventTest
{
	public event Action Completed;

	public void DoSomething()
	{
		for(int i = 0; i < 10; ++i)
		{
			Debug.Log(i.ToString());
		}
		if (Completed != null)
			Completed();
	}
}

The event is defined using Action as the delegate type, with the variable name Completed. After creating an instance of the class, the event is assigned to using the += operator, which is how you add your own delegate to the event, and then the DoSomething method is called. This method does its stuff then calls Completed, assuming it’s been assigned to, which in turn invokes the lambda we assigned to it.

There is a way to omit the null check by assigning an empty delegate list to the event, but that forces creation of the delegate, which causes extra memory overheads, so be aware of that.

To do it, you simply use this:

public event Action Completed = delegate{};

When to use events and when to use delegates is a fairly interesting design choice, but basically boils down to this: if it needs to be a public class member, use an event, otherwise, use a delegate. Events won’t work as parameters to functions as they’re a set of functions themselves, so bear that in mind.

Put all of the above together and you can create some fairly amazing things.

And with that, part two is concluded!

Posted in C#, Unity | 1 Comment

Delegates, events, lambdas and all things callbacky! (Part 1)

Callbacks… are awesome. Really awesome. You just won’t believe how vastly hugely mindboggingly awesome they are…

Ahem.

Anyway, I get asked a lot how to do callbacks, or how to do things which scream callbacks to me, so today I’m going to try go from beginner to midlevel in one post.

So to start, what is a callback?

In the most basic terms, it’s a reference to some form of executable code. A basic example would be calling a function when a coroutine has finished, or a user has pressed a button. If you want your coroutine or button code to be reusable, you can’t call the function by name, you’ll need to tell it which function you want to call from whatever starts the coroutine or button.

And a delegate?

A delegate is a type which holds such a callback, or, heck, even multiple callbacks.

So let’s start with a few simple examples of how to declare your own delegates, as the rest of this article I’m going to use built in ones.

delegate void MyDelegate();
delegate void MyOtherDelegate(bool result);
delegate bool MyReturningDelegate();

So, let’s look at them in order.

The first one is probably the most simple delegate possible – it wants an empty method which doesn’t return anything.

The second example isn’t much harder – it wants a method which takes a bool as a parameter and doesn’t return anything.

The last one is similar to the first one with one exception – it doesn’t take parameters, but it needs to return a bool value.

In all three cases you’re simply defining the structure of the delegate. Think enum or even class – you define the type, then later you create instances of it, and that’s exactly what you’re doing here.

Now, a simple example using one of these:

void Start()
{
	MyOtherDelegate callback = MyCallbackMethod;
	callback(true);
}

void MyCallbackMethod(bool result)
{
	Debug.Log(result);
}

This assigns the MyCallbackMethod signature to the callback (Which will resolve to be the second example delegate above) and then calls it, passing true. This will call MyCallbackMethod, causing “true” to be printed by the Debug.Log.

Since this is a simple snippet, it’ll look a little daft – why not just call MyCallbackMethod(true) ?

The reason is that this may not be in the same class. The actual method that is called in the end may not even be known until runtime. Or, even worse, it may need to be called after a button is pressed in a completely different function which doesn’t know about your own code.

We’ll get to those points later, but first, the next step – anonymous functions (the delegate way).

Anonymous functions are basically a way of writing function code inline in the place you’re using it, instead of the function being located elsewhere.

A quick example, similar to the last one:

void Start()
{
	MyDelegate callback = delegate(bool result) { Debug.Log(result); };
	callback(true);
}

It’s shorter than the last example, and does the exact same thing, calling Debug.Log(result). The format for anonymous functions like that is delegate(parameters) { code, with a return when necessary}.

There is also another type of anonymous function called a lambda, but I’m going to leave that for the next (more advanced) post.

So now onto my original promise of using built in delegates!

There are two very useful delegates to learn, Action and Func. Both of these take from 0 to 16 parameters, the types of which you specify with generic types. Func also takes another generic type which is the return type.

The most basic form of Action and Func are defined as such:

delegate void Action();
delegate TResult Func();

The Action one should be extremely easy to pick up, it’s identical to the original MyDelegate above. Func should be fairly easy if you know generics, otherwise it’s just this – its return type is whatever you pass in as the generic type.

Here’s Action in action (and Func thrown in for good measure):

void Start()
{
	Action callback = delegate() { Debug.Log("Called"); };
	callback();

	Func callbackFunc = delegate() { return false; };
	Debug.Log(callbackFunc());
}

The benefit of this is you no longer have to go looking in the code to find out what the delegate parameters and return type are – it’s given to you right there and then.

So, onto a practical(ish) example:

using System;
using UnityEngine;

public class Callbacks : MonoBehaviour
{
        //this is the delegate we'll be using.
        Action<bool> callback;

        //these two are to show the result after we've clicked
        bool hadCallback = false;
        bool callbackResult;

        void Start()
        {
                //assign the OnConfirm function to the delegate
                callback += OnConfirm;
        }

        void OnGUI()
        {
                //this is to draw the result of the confirm after clicking
                if (hadCallback)
                {
                        GUILayout.Label("Last result of confirm: " + callbackResult);
                }

                GUILayout.BeginHorizontal(GUI.skin.box);

                if (GUILayout.Button("Ok", GUILayout.Width(100)))
                {
                        //call the callback function with true to say we clicked ok
                        callback(true);
                }
                if (GUILayout.Button("Cancel", GUILayout.Width(100)))
                {
                        //call the callback function with false to say we clicked cancel
                        callback(false);
                }

                GUILayout.EndHorizontal();
        }

        //this will be called when ok or cancel is clicked
        void OnConfirm(bool result)
        {
                callbackResult = result;
                hadCallback = true;
        }
}

The above example pulls together everything I’ve mentioned so far. It has an Action variable for storing the callback, an OnConfirm method to handle the callback, and a couple of buttons which call the callback with either true (ok) or false (cancel).

Again, this isn’t really necessary in this example as I’m doing it all in a way which would be easy to hardcode, but that’s not the point of examples; If I were to put the code into a more abstracted popup class which creates a popup, waits for input then notifies you when the user clicks a button, it would be perfect.

That wraps up part one of this miniseries, next time: Lambdas, events, the basics of functional programming and more delegatey goodness!

Posted in C#, Unity | 5 Comments

Sane Data Encapsulation

So, you start up your brand new copy of Unity, and start tapping away, and MAGIC! Public variables show up in the editor.

Fast forward a few months, or even years, and you’re probably still using public variables everywhere, or at least to get them to show up in the inspector.

Now, you may be wondering why this is a bad idea; Unity is being magical after all, filling in your variables for you!

Now think about this: something, somewhere in your code starts changing your variable at runtime, and you have no idea where. Do you go through the entire codebase, searching for it? Use your code editor to find all references of it being used, and hope to get lucky?

Or this: you’re changing a variable, but no matter what you set it to, it’s always doing the same thing. *facepalm* It was a public variable, and unity was setting it for you.

Securing your code from silliness like that is actually fairly easy, and definitely something I would recommend for anyone who has outgrown being a Unity beginner.

First off, make all of your variables private. All of them. Even that one, yes.

This stops other code from being able to manipulate the variables (without resorting to dynamically setting them, but that’s another story entirely). Now, your variables don’t show up in the inspector! Well let’s fix that:

//C#
[SerializeField]
private Transform myTransform;
//UnityScript
@SerializeField
private var myTransform : Transform;

Yay! They’re back!

And now you can immediately see which variables should be shown in the inspector and which shouldn’t without having to think twice. You could even put the attribute on the same line as the private variable to make it doubly obvious.

Anyway, other code can’t access the variables now, so let’s get on with the real meat of this post: Properties and/or methods

Methods are the old-school way of giving access to data in a controlled way – you can make a function to set the variable, and a function to get the variable. The benefits of using this over public variables are numerous – you can specify different levels of access for getting and setting (e.g. public get, private set), the ability to add more code into the get/set (e.g. Debug.Log(“Variable accessed!”); to figure out where the code is being got and set from), and many other reasons.

A quick example (For brevity, C# only):

[SerializeField]
private Transform myTransform;

protected void SetTransform(Transform newTransform)
{
	Debug.Log("Setting myTransform to " + newTransform.name);
	myTransform = newTransform;
}

public Transform GetTransform()
{
	Debug.Log("myTransform accessed!");
	return myTransform;
}

It’s a little bit more code than a single public variable, but much less prone to random bugs, and much easier to debug and add functionality to.

Now, Properties!

Properties have been in .NET since the very beginning, and they’re a pleasure to use. They give you all the benefits of methods, while seemingly acting like variables. Unity makes great use of them, nearly all of Unity’s “variables” are actually properties.

They work in both C# and UnityScript, though much more easily in C#. Here’s an example of declaring one in both languages:

[SerializeField]
private Transform myTransform;

public Transform MyTransform
{
	get
	{
		Debug.Log("Accessing myTransform");
		return myTransform;
	}
	protected set
	{
		Debug.Log("Setting myTransform to " + value.name);
		myTransform = value;
	}
}

public int Test { get; set; }
class MyClass
{
	@SerializeField
	private var myTransform : Transform;

	public function get MyTransform() : Transform
	{
		Debug.Log("Accessing myTransform");
		return myTransform;
	}
	protected function set MyTransform(value : Transform)
	{
		Debug.Log("Setting myTransform to " + value.name);
		myTransform = value;
	}
}

Now, you may be wondering why I declared a class explicitly in my UnityScript snippet, and rightly so; You cannot (As of writing this post) use properties in UnityScript with implicitly created classes (i.e. script files without an explicit class definition).

Onto the syntax. The C# one is probably new if you’ve never seen a property before. You declare what looks like a variable, then add in a block after, with get and/or set accessors. The accessors contain the code to get or set the value however you like, and have an implicit variable called value for the set accessor to let you assign to your internal variable. I also added in a second property called Test, which uses the C# 3.0 auto-implemented (or automatic) property syntax. This let’s you quickly make properties which completely hide the backing field (the variable it assigns to), stopping you from doing anything silly with the variable itself, and making code shorter.

For UnityScript, the syntax looks familiar up until the get and set keywords. These tell the compiler to use the functions as accessors to a property.

To use them, in both languages, you simply treat them like they were variables:

MyTransform = transform; //set
var theTransform = MyTransform; //get

For C#, using properties is a no-brainer. They’re generally the standard for giving access to your variables, and fairly easy to implement. For UnityScript, less easy to implement, the implicit class issue being the main reason to think about using methods instead.

So, in conclusion – public variables bad, public methods and properties good.

Posted in C#, Unity, UnityScript | 4 Comments

Extension Methods

My first real post is going to be about extension methods. While they’re fairly normal to see in the .NET development world, I tend not to see them much when it comes to Unity, so here’s my quick primer on them.

Though they can be used with Javascript, they can’t be used in the much more elegant way C# does them, nor can they be declared in Javascript, so this post is really for C# only.

So, what can they do for you?

The idea behind them is allowing for adding functionality to a preexisting Type, regardless of whether you have access to the source or not. This means that you can add your own methods to the built in Unity classes (amongst other things) to make using them more manageable.

Note that I said Type, not class. You can use them to add methods to interface types as well, which you can’t do in the interface itself.

Now, for an example; Imagine that you dislike the fact that Rigidbody has no simple way to set its position via an offset instead of using a world position. To get around this, you could code your own extension method to do it:


using UnityEngine;

public static class RigidbodyExtensions
{
	public static void Translate(this Rigidbody rigidbody, Vector3 offset)
	{
		Translate(rigidbody, offset, Space.Self);
	}

	public static void Translate(this Rigidbody rigidbody, Vector3 offset, Space space)
	{
		if (space == Space.Self)
		{
			//rotate the local space offset into world space
			offset = rigidbody.rotation * offset;
		}
		rigidbody.position += offset;
	}
}

Now, if you don’t understand all of the syntax, don’t worry, I’ll get to that soon.
My example shows two Translate methods, both with the same syntax as Transform.Translate. It very simply sets the position of the Rigidbody, using the original Rigidbody position and the given offset, rotated into world space if Space.Self was wanted.

The two things to look at regarding extension methods are the class definition and the method definitions.

For extension methods to work, they need to be placed inside static classes. This (besides the technical reasons behind it) helps to keep the extension methods away from your other code, preferably in obviously named classes with something like the word Extensions on the end.

For the method definition, extension methods need to be static, and their first parameter needs to have the word ‘this’ before the Type. The this parameter is not actually passed to the method by the calling code, but is instead assigned with the object the extension method is called on.

To use the above methods is fairly simple:


//move forward by 1 meter per second (if called in FixedUpdate)
rigidbody.Translate(Vector3.forward * Time.deltaTime);

//move by Vector3(5, 5, 5) in world space
rigidbody.Translate(new Vector3(5, 5, 5), Space.World);

Note the lack of the static class, or the first Rigidbody parameter for the function.

This technique can be applied to many situations, giving you a large boost in productivity with the right extension methods.

If you want to see some more examples, check out my extension methods on the wiki:

IsVisibleFrom Renderer Extension
A simple extension to check if a Renderer is visible from a specific Camera

LayerMask Extensions
A set of extensions to help create and manipulate LayerMasks by name

Posted in C#, Unity | 2 Comments

Mu.

Welcome to my new blog.

I’m Mike, and I’m a professional Unity3D developer. In the upcoming posts I’ll be expressing the interesting (and insane!) things that spring to mind about computer game development.

My first tidbit of the day:

Mu.

That is all.

Posted in Mu, Uncategorized | 2 Comments