Extend GameObjects with custom methods
Being able to add custom methods to GameObjects can really make your code more readable.
In cases when something happens to an object and there can be multiple outcomes, like when a GameObject collides with another GameObject, I sometimes find my self writing code like this:
Of course, there might be many ways of solving this in better ways. Let's for the sake of the example stick with it.
With the help of extension methods, this piece of code can be written like this:
You may have noticed that I have just used two functions that doesn't normally exist on GameObject. So, how do we extend GameObjects with our own functions? Do like this:
Create a static class without extending any other class, and add publicly available static methods for each function you want to extend GameObject with. The trick is in the method parameters. Notice the use of the this keyword. That's all there is to it.
There's more info on C# extension methods to be found on Microsoft's page Extension Methods.