How to randomly choose an Element of an Enumeration C# Unity3D


Unity quick tip

I recently had the problem that I was working with enumerations and at some point I wanted to choose an entry randomly from my Enumeration. In the following I would like to show you how you can solve this task.

Thats how my Enumeration looks like:

	public enum Direction : int{
		North,
		East,
		South,
		West
	}

The main problem is that the default classes don’t offer a method for getting the length of an enumeration thats why we have to add the System namespace at the top of the script.

using System;

The following function is now returning an item randomly from my Enumeration Direction.

	private Direction RandomDirection(){

		return (Direction)(UnityEngine.Random.Range(0, Enum.GetNames(typeof(Direction)).Length));
	
	}

Thats it for this quick tip. I hope that it is useful for you! 🙂

Cheers Alex

Advertisements

2 thoughts on “How to randomly choose an Element of an Enumeration C# Unity3D

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s