Clean-Up Day: New Tricks with C#

Sie sind hier

Since I’m currently cleaning up my code to hand it in with my project, I figured I could write some of the stuff down I learned during my work on our game.

All of it applies, of course, to C#, and was used in Unity 3D.

Checking for a type

Using the is keyword, you can easily check whether a certain object is of a desired type. Also, you should be aware of the as keyword, that allows you to cast an object as something else (given that this is possible).

if (obj is ISource) { ISource s = obj as ISource; if (!s.isEndpoint) { Connect (s); } }

Modelling Behaviour Over Multiple Frames Without Update()

Sometimes, you need to model some behaviour over several frames (like fading stuff in or out), but doing it in Update() or FixedUpdate() would require unwieldy if constructions.

So … coroutines to the rescue! Using WaitForFixedUpdate(), you can model a behaviour over several frames without using FixedUpdate(), and quits as soon as it is done.

float i;

private void SomeMethod() { // do some stuff here i = 1f; StartCoroutine(FadeOut()); }

private IEnumerator FadeOut() { while (i > 0f) { yield return new WaitForFixedUpdate(); i -= 0.1f; } }

 Delegates – The Easier Way

I wrote about delegates before, explaining how they could be used. I proposed that a new delegate had to be defined whenever you would want to use one.

Turns out, this is not even necessary – the System namespaces already has a delegate prepared for you, called Action.

using System;

public class Example { private Action DelegateMethod;

private void Method() {


In case you use some parameters in your method, you could also use Func, which has parameters prepared.