The most important extension method you’ll never write.

As game developers, we frequently need to randomly generate things, whether it’s picking a power up to spawn, or choosing between enemies. Regardless, of the use, one of the most common forms of random generation in a game is picking an object from a list of potential candidates at random. This happens so often that I wrote an extension method to do it for me, so if, like me, you’re a C# game developer, save yourself some time and headache and use this:

This will then pick a random item from any collection and return it (or null / the default value for a type if there are no items).

Usage is like so:

Best part is this will work on anything that implements IEnumerable , which is pretty much any C# collection, array, LINQ result, whatever.

Leave a Reply

Your email address will not be published. Required fields are marked *