Creating Class Extensions in Unity

Tag: Unity

Category : C# , Unity

So… you’ve got a useful method that does some pretty cool stuff but you don’t know where to put it. You’ve probably labeled this in your mind as a helper method which can be easily defined as a method that specifically aids in one or more repetitive tasks.

Great you say.. lets just create a new C# script and call it HelperMethods and throw it in there. This is not a bad idea and honestly I used to do this a lot myself but… there is a more elegant approach to this.

What if there was a way that you could add functionality to an already existing class? What if for instance you wrote a method which could easily be part of the Random class that is part of the UnityEngine?

This is actually exactly what I did. I wrote a method that returns not just a random range between min and max values but found that I needed to return a random number with specific numbers being excluded between the min and max values.

This is a perfect example of a method that should be an extension method to the Random class. So how do we do it? Its actually really simple. First know that we can place all of our extension methods within one simple class. Lets call this class ExtensionMethods.

Read More

Show Some Love

Support The Weekly Coder on Patreon!

WeeklyCoderTV

Recent Popular Info

About:
This channel is all about coding. We will mostly post tutorials on making games with Unity 5 and above. Other posts will include tutorials on specific game mechanics and whatever else we feel like talking about.

Don't be shy.. If you have a question, leave a comment. If you you'd like to see a specific tutorial feel free to request it. If we think its worthwhile, then we may just do it.

Please don't forget to click the like button and remember to subscribe. Feel free to support our channel and the awesome content we create.

Total subscribers:
767

Total uploads:
71

Total upload views:
89.1 thousand

Follow me on Twitter

Subscribe

RSS Feed

Blog Authors