web analytics

How to use C# Enum in Unity

In C# enums are there own types , just like classes .Enums are strongly typed constants. So you can only declare them in global scope or within a class scope. Enum makes things easier to understand.

C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.

Declaring Enum 

enum <enum_name>

{ enumeration list };

Why to use Enum : 

1.  Enums are values. We can use enums to index arrays.
2.  Enums are fast.
3.  Enums enhance clarity and reduce the probability of invalid constants.
4.  We use them to represent constant values such as integers in a consistent way.
5.  They are essentially unique types that allow you to assign symbolic names to integral values

For example, what type of code would you rather work with a set of difficulty level named Low, Medium and High or the set of integers 0, 1 and 2 that mapped to the same values, respectively?

Eg.

Lets declare enum for game states and use them

public enum GameState{
   Loading,
   Running,
   Paused,
};


To use it just create a variable and use it

GameState _gameState ; // Create a variable 

switch(_gameState){
case GameState.Loading : // DO stuff
          
case GameState.Running: // Make the character run

case GameState.Paused: //Do stuff when paused
}

OR
Lets say we have different weapons

puiblic enum WeaponType{
  Sword,
  Axe,
  Bow,
  Dagger
};

public class Player: Monobehaviour{
//Now lets say we want to deal damage depending upon what weapon player has.

WeaponType weaponType;

void Start(){
      weaponType = WeaponType.Axe; // Let's say the player owns Axe right know 
}


public void Damage() {

switch(weaponType){
     case WeaponType.Sword : damage = 100f; break;

     case WeaponType.Axe : damage = 70f; break;
        
     case WeaponType.Bow : damage= 45f; break;

     case WeaponType.Dagger : damage = 60f; break; 
     }
  } 
}

 

You can see how readable the code is .This is way much better than using strings for the names (possibility of making error).

* Its way better than assigning any integer value or string for every weapon .

i.e  weaponType = “Sword”  (Possibility of making errors by spelling the string wrong ) 

You can see the enums in inspector like this

c# enum c# switch enum enum c# c# enum to int

c# enum, c# enum  c# switch enum, enum c#, c# enum to int

C# Enum to Int Conversion :

We can use enums to index arrays.
int axeIndex =(int) WeaponType.Axe;

axeIndex will contain value  1

c# enum , c# enum  c# switch enum  enum c#  c# enum to int

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

private WeaponType RandomWeapon(){

return (WeaponType)(UnityEngine.Random.Range(0, System.Enum.GetNames(typeof(WeaponType)).Length));

}

You may also like...

Leave a Reply

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