Serious C# scripting bug related to consts

So, I was getting some wacky behavior in my game and I was able to isolate it to this code:

        const float variation = .5f;

        float minValue = -variation;
        float maxValue = variation;

        Debug.Log(string.Format("minValue: {0}, maxValue: {1}", minValue, maxValue));

One might expect to get an output of -.5 and .5, but nope… Unity gives:

minValue: 0.5, maxValue: 0.5
UnityEngine.Debug:Log(Object)

Tisk tisk Unity, that does not match what we get in .NET. But taking out the const fixes it. In other words:

        float variation = .5f;

        float minValue = -variation;
        float maxValue = variation;

        Debug.Log(string.Format("minValue: {0}, maxValue: {1}", minValue, maxValue));
minValue: -0.5, maxValue: 0.5
UnityEngine.Debug:Log(Object)

Careful if you use consts inside your methods. This is a common way in .NET to avoid magic numbers and get the performance benefit of const operations without cluttering your fields and intellisense.

Is this a known issue that is being fixed? Could cause some pretty nasty bugs.

as you realized thats a dot net behavior so if it goes wrong its a mono 1.2.5 bug and nothing unity could even impact (mono 1.2.5 had quite a few bugs)

Unity 3 uses Mono 2.6+, which has a much more solid compiler that will throw errors on incorrect syntax and alike and in relation to handling like this

Or you can try to multiply the variable to (-1)

float minValue = (-1) * variation;

Right there are workarounds, the issue at hand is that folks will write this code and expect it to work…and it’s a difficult problem to solve - especially since you have to reply on Debug.write instead of a proper step-through debugger. (Yeah, I know, 3.0).

Holy smokes, that’s one heck of a compiler bug! :smile:

I gave that a try out of curiosity, and got:

minValue: -0.5, maxValue: -0.5

Which is still wrong, but wrong in a different way, which is interesting. Using “-variation” made the constant negative in my case. Not very constant if you ask me…

–Eric

I actually reported this bug to Mono some time ago and they eventually got back to confirm it had been fixed. It’s just that Unity hasn’t updated the C# compiler since then (until version 3.0).