Last night I was working on a C-Sharp project trying to code around GameObjects hitting each other. I wanted different gate types (e.g. wood, stone, metal) that could be broken down by different weapons (e.g. club, sword, axe).
For detecting the collisions on the GateManager I was using tags for each gate. So for example:
void OnTriggerEnter(Collider collider) {
switch (gameObject.tag) {
case "WoodenGate":
...
case "StoneGate":
...
The above code isn't exact but should give an idea. It felt wrong to have each gate type set as a different tag (if every gate type has a different tag and every material type has a different tag, etc, then I will end up with hundreds of tags).
So I came up with an alternative. I set up an enum of GateType and created 3 values (WoodenGate, StoneGate, MetalGate). I then attached a public GateType property to the GateManager class. This allowed me to select which enum was relevant to each prefab within the 'Inspector' window of unity. It was very neat and I was really happy.
Then a problem arose: I added a 4th enum halfway up the list (e.g. GlassGate). Because the enums are simply int values, the 3rd item was no longer MetalGate but was now StoneGate. This meant the metal gate prefab suddenly had a GateType of stonegate. Which broke my game.
Apologies, for the wordy question, but my question therefore is how should I best label and identify lots of different types of items? I don't want to use tags (because I would need too many) and I don't want to use enums (because they form the brittle issue when used in conjuction with the unity inspector.
I assume this must be a common requirement for many games (e.g. in games you can use your pickaxe on lots of different gameobjects to gathering different resources) so just wondering the best practice?
Enums are the most convenient way to do this. Add an index to the enum value and increment it manually.
public GateType gateType;
public enum GateType
{
Wood = 0,
Stone = 1,
Brick = 2
}
Now if you want to add another one in the middle of the 'list' do it like this:
public GateType gateType;
public enum GateType
{
Wood = 0,
Metall = 3,
Stone = 1,
Brick = 2
}
Unity should keep the correct values on your objects, since you added the index.