# Understanding mathf.Clamp in Unity

There is no game development with mathematics. We see multiple mathematic calculations during the game development process. Mathf in Unity is the combination of all mathematic functions that you will need for your game. Mathf is inbuild in the Unity engine namespace so, you don’t need to add any to use mathf.

Mathf has lot of static functions. You can get the complete list from Unity docs. In this tutorial, we are going to cover only the frequently used function with examples.

## Mathf.Clamp

Clamp funciton as the name suggests clamps the value between the given range. Mathf takes three arguments. The first one is the variable which needs to be clamped, second input is the minimum range and the last input is the maximum range.

Mathf will return the minimum range if the variable value is less than the minimum range and will return the maximum value if the variable is larger than the maximum range. If the value is between the range, then the output will be equal to the variable.

Example code

``````using UnityEngine;

public class Mathf_example1: MonoBehaviour
{
float my_value=0f;
float min_value=10.0f;
float max_value=20.0f;

void Update()
{
my_value+=1.0f;
my_value=Mathf.Clamp(my_value,min_value,max_value);
Debug.Log(my_value);
}

}``````

mathf example output

Tip: If you need to clamp a value between 0 and 1. Then you can use Mathf.Clamp01. It takes only one variable as input and clamps the value between 0 and 1.

## How to clamp a Vector3 in Unity

Let’s use mathf and try to clamp position of a game object in the y axis. This is similar to Unity lerp but you only clamp the value in this case.

1. Create a new script call vector_clamp.
2. Add it to the game object you want to clamp.
3. Set the value where you want to clamp the vector 3 axis.
4. Play the game and see the result.
``````using UnityEngine;

public class vector_clamp : MonoBehaviour
{
Vector3 pos;
float height_restriction=10f;
// Start is called before the first frame update
void Start()
{
pos=transform.position;

}

// Update is called once per frame
void Update()
{
pos.y+=0.5f;
pos.y=Mathf.Clamp(pos.y,0,height_restriction);
transform.position=pos;

}
}
``````

This site uses Akismet to reduce spam. Learn how your comment data is processed.