The Importance of C# Extensions in Unity


Unity is a great tool for building games, it offers a ton of features and makes it almost painless to export your game to multiple platforms. However it it still has some shortcomings, and you can’t expect it to do everything you need right out of the box. Today we’ll discuss C# extensions and how they can be used in Unity to cut your design time and make your code cleaner. We’ll discuss some of the most useful ones we’ve used during the development of Rogue Star Rescue.


What is an extension?

Simply put, an extensions adds a public function to a class you didn’t write. In Unity this is especially useful because we don’t want to override the GameObject or Transform class every time we need some extra functionality. They are defined as static functions and use the ‘this’ keyword to reference the instanced object the function is applied to. The declaration looks like this:

public static ReturnClass extensionFunctionName(this ExtendedClass object) {}

Vector Extensions

In 2d games Vector2s are used almost everywhere. The problem is that they don’t always ‘fit’ with a lot of the 3d functions of GameObject, causing a lot of compiler errors/warnings from casts. We can use some extensions to make life easier. 
(CODE) (I can't paste code here, so please refer to my original devlog to see the lines) 

Furthermore if you’re using Tilemaps you’ll need a lot of Vector3Ints. These neighbour functions are very helpful for procedural tile generation logic.

(CODE)

List and Enumerable Extensions

Any game is going to have a lot of List and Enumerable objects. Below are some useful extensions.

(CODE)

GameObject and Transform Extensions

GameObjects and Transforms are at the core of any Unity game. Unfortunately they are still missing some conveniences that makes them hard to work with. The following extensions can make working with them much smoother.

(CODE)

The great thing about these extensions is that they can be reused in your future projects! I like to put them all in one file but you can just as well use multiple files, depending on how complicated your game is. Rogue Star Rescue’s code base would be much larger without them, so use them wisely to keep your project more maintainable.

Get Rogue Star Rescue

Buy Now$14.99 USD or more

Leave a comment

Log in with itch.io to leave a comment.