const strings vs static string getters vs enums?

Hi all. I would like to know which way is the most standard to show collections like weapon types,names, items, etc?

public enum WeaponType{
   None=-1,
   Weapon1,
   Weapon2
}

public class WeaponType{
   public static string weapon1{get{return "Weapon1"}}
   public static string weapon2{get{return "Weapon2"}}
}

public class WeaponType{
   public const string weapon1= "Weapon1";
   public const string weapon2= "Weapon2";
}

//define inside weapon class
public class Weapon{
   public const string weapon1= "Weapon1";
   public const string weapon2= "Weapon2";
}


//define inside weapon class
public class Weapon{
   public static string weapon1{get{return "Weapon1"}}
   public static string weapon2{get{return "Weapon2"}}
}

If I use enum, I need to write “[SerializeField] WeaponType type” and If I change, add or remove types in the enum, I need to correct all of them. (ugly solution is to bind enums to numbers), so I can add and remove them without requiring to assign them again.

If I use strings, I need to write “[SerializeField] string type” and if I change the type name, I have to correct it.

The final way is to use ScriptableObject in unity

Use const, not the static property. The static property is just returning a const (inline strings like that ‘return “Weapon1”’ is just treated as a const by the compiler). All you’ve done with the static property is add a method call.

As for string vs enum, I’d say that’s just preference. I would say enums are nice because unity directly supports a dropdown for them in the inspector. But strings are also very helpful in many ways too.

Then for if the string is in a separate class vs the same class. I’d say that fully depends on your design. If you have a generic base ‘Weapon’ class it is convenient to have them defined there (usually I go with the C style upper-case naming of Weapon.WEAPON1 or something). But if you instead have a interface like IWeapon instead, a WeaponType static class if useful. Again, that’s just preference, and really there’s no huge difference.

2 Likes

Perfect. Yes I agree. If I have a base class, I prefer to add them inside it as well.
It is right. Constants should be started with upper-case letter.
Enums have problems in the inspector, when I add something to them or remove based on ordering.
Thank you.