Mathf.Clamp() can change variable type? (float to int)

Alright, i just want to know if this should be happening or not.

First of all, this works just fine

otherScript = GetComponent("otherScript");
otherScript.floatVariable += 0.2;

When I retrieve a float variable from another script like this:

otherScript = GetComponent("otherScript");
otherScript.floatVariable += 0.2;
otherScript.floatVariable = Mathf.Clamp(otherScript.floatVariable,0,25);

…if I do that then the floatVariable, which is float in the other script, becomes integer in our current script, and += 0.2 doesn’t work because it rounds it up as += 0

so to fix it I’d have to change 0 and 25 to 0.0 and 25.0 inside Mathf.Clamp

otherScript = GetComponent("otherScript");
otherScript.floatVariable += 0.2;
otherScript.floatVariable = Mathf.Clamp(otherScript.floatVariable,0.0,25.0);

On the last line, inside Mathf.Clamp() I used 0.0, and 25.0 instead of 0 and 25, that way floatVariable keeps being a float variable.

Is this a bug? or is it due to some sort of knowledge i’m missing, becuase Mathf.Clamp() doesnt reguraly behave like this, this only happen when bringing variables from other scripts.

Is the variable actually called otherScript in the real code? (It would seem to have the same name as the class if so.) Also, in the otherScript.js file, are you declaring the floatVariable’s type explicitly or by assignment?:-

var floatVariable: float;   // Explicit
var floatVariable = 0.0;   // Assignment

It looks as though the value returned by the integer version of Mathf.Clamp is dynamically changing the type of floatVariable. This is probably a bit of surprising but consistent behaviour rather than a bug. However, it’s worth checking out further.

Notice that there is no Mathf.Clamp(float, int, int) defined… Unity (or rather, the .NET runtime) has to infer which of the two available methods you intended to invoke. It does that based on the types of the arguments, not the type of the variable you assign the result to.

It looks like the Mathf.Clamp(float, int, int) call is being coerced to Mathf.Clamp(int, int, int) rather than Mathf.Clamp(float, float, float). I would expect the oposite (since coercing a float to an int is a lossy operation, it would require an explicit cast in C#… UnityScript, though…)

Explicitly passing 3 floats when you want a float result is the safest thing to do, and also makes the intent of the code clear.