Minimum and Maximum values

Hi! I’m very new to scripting in Unity, so please forgive the stupid question.

I need to set minimum and maximum values for a var, in order to stay within a specific range (e.g. 1 - 10).

I’ve got a camera set up that allows me to zoom in and out using the mouse scroll wheel. This is determined by a var called “distance”. It works fine, but the player would be able to zoom in and out infinitely. That’s why I want to set min max values for “distance”.

check the function >> Mathf.Clamp

this may work for you need maybe.

1 Like

Thanks for the reply. I’m sorry I’m very ignorant when it comes to scripting, but I AM learning.

I’ve tried the Mathf.Clamp function, but it doesn’t seem to work. I don’t think I’m using it correctly.

I typed:

var distance = Mathf.Clamp(1, 0.3, 2);

The script runs, but the min and max values don’t seem to affect. Please help!

The first parameter for the clamp function should be the variable you wish to be restricted.

As written you are trying to make a constant (1) fall between the values 0.3 and 2.

If distance is being modified elsewhere and may be outside the 0.3 → 2 range, you need to write something like…

....
//increment distance
var distance=distance+1; 

//ensure distance will not go beyond 2
distance = Mathf.Clamp(distance, 0.3, 2);
....

What I do is this:

function Update()
{
 if(distance > 10)
{
     distance = 10;
}

 if(distance < 1)
{
    distance = 1;
}
}

So, if the distance variable becomes more than 10, it will set it to 10. If it becomes less than 1, it will become 1.

As suggested before, you’d better use Mathf.Clamp.

What you wrote is good, but can hold on one line :

distance = Mathf.Clamp (distance, 1, 10);
1 Like

Hey thanks a million! I got it working!

It was my own stupidity as well. Instead of typing 1.0 I just typed in 1, and so it automatically declared it as an int.

I used the Mathf.Clamp function, and it works beautifully!!!

Why do all that, when there’s a simple function available that does the same thing? As suggested previously, just use Mathf.Clamp().

Also, even if one was to do that, it would be better as

if (distance > 10.0)
else if (distance < 1.0)

Otherwise, without the “else”, it always has to evaluate both “if” statements, which is a waste of CPU cycles, since the second one can’t ever be true if the first one is true. (Not a lot of CPU cycles, to be sure, but it’s such a simple optimization that one might as well get in the habit of doing it.) Also it’s slightly faster to use the correct type for the numbers, namely floats instead of ints in this case. Otherwise they have to be converted, which again is a waste, and again is not much of a waste, but it’s so easy to do it optimally that one might as well. Also it makes the code clearer as to what types you’re dealing with exactly.

–Eric