Apache81
Apache81

Reputation: 241

Unity C# (Mono) enum fault

I'm defining this code:

public enum ModelType {
    R4,
    W6,
    W8,
    W9,
    X9
}

and I'm using this function in another script:

public void RequestModel(ModelType type, Size size) {
    Debug.Log("Requesting " + type.ToString() + " at size " + size.ToString());
}

the output result is:

Requesting 9 at size 4

If I change the code in

Debug.Log("Requesting " + (int)type + " at size " + size.ToString());

I'll get the same result. Does someone know what's going on?

I have to say that the first time I wrote the enum it was like:

public enum ModelType {
    EX1,
    EX2,
    EX3,
    EX4,
    EX5,
    EX6,
    EX7,
    R4,
    W6,
    W8,
    W9,
    X9
}

but I got rid of the EXes because I don't need them anymore.

I also tried to add again the EXes and I got the outputs:

Requesting W8 at size 4  // if I use ToString()
Requesting 9 at size 4   // to print the enum value

that are ok.

I really don't know what to do. I tried to reimport all, restart Unity and Visual Studio but if I delete the EXes nothing will work properly.

Any ideas?

EDIT: sorry guy, I forgot to mention that in the code I'm calling the function as

RequestModel(ModelType.W8, Size._4);

having the wierd result already described.

Upvotes: 1

Views: 1061

Answers (2)

Apache81
Apache81

Reputation: 241

I found the problem: in an initialisation method there was a declared BUT NOT INITIALIZED variable:

ModelType currentModel;

I don't know for what reason but that variable just got the strange value of 9 (corresponding to the old value of the W8 enum) and the initialization method was parsed before the function call described in the question.

I solved the issue by initializing the variable.

Thanks to everyone guys !!! :)

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564471

With the "EX" options in place, W8 will map to a value of 9. When you removed them, it now maps to 2. If you're loading ModelType type from something that had the value serialized as 9, it would explain the difference - type would actually be 9, which no longer exists in your enum, so ToString will print the numeric value.

I recommend fixing your enum to specify the values explicitly, as this will make it backwards compatible.

public enum ModelType 
{
    R4 = 7,
    W6 = 8,
    W8 = 9,
    W9 = 10,
    X9 = 11
}

Upvotes: 2

Related Questions