Mathf.Clamp01 always return 1

At first time ZerotoOne() is called, value of i gradually increases from 0 to 1. However, i will always be 1 after that. Is it possible to reset Mathf.Clamp01() to start from 0 again?

var state:int = 1;
function Update () {
	if (state == 1)
	{
		state=2;
	}
	if (state ==2)
	{
		ZerotoOne();
	}
}

function ZerotoOne()
{	
	var i:float = Mathf.Clamp01(Time.time*0.3);
	Debug.Log(i);
	if (i <= 1.0)
	{
		if (i == 1.0)
		{
			state = 1;
		}
	}
}

don’t use Time.time? That value constantly increases through the scene, so after the first second, it will always be > 1.0

var timer:float = 0.0;

function Update() {
   timer += time.deltaTime * 0.3;
}

should do the trick, and you can reset it by a simple “timer = 0.0;”

If your trying to have it loop from zero to one repeatedly you’d want to change line:

var i:float = Mathf.Clamp01(Time.time*0.3);

to

var i:float = Mathf.Repeat(Time.time*0.3f, 1.0f);

the change will always be between 0 and 1 just it will loop going 0 … 1 0 … 1 you can use Mathf.PingPong to have it go 0 … 1 … 0 … 1

if you wanted to have it reset at times you could do what Tom suggested or you can have a var startTime : float = 0; then use it like so:

var i:float = Mathf.Clamp01( (Time.time - startTime )*0.3f);

and then you would just set startTime to Time.time when you wanted the values returned by Clamp01 to start off as zero again.

1 Like