Tuesday 24 September 2013

How to use enums to store keys for scripts in Unity3D

Everyone love strings. Especially those hard-code when you can find all references to this one which you're looking for...
How much I love reading such code and often fix it... This is almost the best thing after magic-classes with thousands of lines and no comments.

<Sarcasm off>

But lets back to the our topic...

What is "enum"? And why should I use it?

Enumerated type (in short enum) is a data type consisting of named constant values. (from Wikipedia).
For example
enum Days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};
Each element has value.
Mon == 0, Tue == 1, Wen == 2, and so on.. This is by default but you can change this: 
enum Days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};
And now Mon == 1, Tue == 2, Wed == 3, and so on...
You can read more about it on MSDN.

And why should you use it?
This is one of many ways to store values and we're interested in something like this:
Days.Mon.ToString();
Now we can easily find all references to this one specific key. This is often comes in handy :)

So lets begin!

First create new class and named it Helper, KeyStorage or something like that. (It's good to know what that class do after looking at the name)
If you'd like to use those all enums globally now you need to do something like that:
using UnityEngine;
using System.Collections;
public class Helper : MonoBehaviour {} 
public enum Tags {
 Card,
 Dice
}
And now in every script you can do this:
Tags.Card.ToString();

Soooooo easyyyyy!


And here are some examples of use:
PlayerPrefs.SetInt(Keys.PlayerScore.ToString(), score); 
Card.tag = Tags.Card.ToString(); 
Dice = GameObject.FindGameObjectWithTag(Tags.Dice.ToString()); 
Player.name = Names.Player.ToString();

I hope now no one will hardcode strings.. This is horrible practice!

And if you're interested in entire scripts you can download it here.

No comments:

Post a Comment