Search Unity

Mathf.Clamp01 always return 1

Discussion in 'Scripting' started by abbc, Mar 16, 2011.

  1. abbc

    abbc

    Joined:
    Mar 12, 2011
    Posts:
    52
    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?

    Code (csharp):
    1. var state:int = 1;
    2. function Update () {
    3.     if (state == 1)
    4.     {
    5.         state=2;
    6.     }
    7.     if (state ==2)
    8.     {
    9.         ZerotoOne();
    10.     }
    11. }
    12.  
    13. function ZerotoOne()
    14. {  
    15.     var i:float = Mathf.Clamp01(Time.time*0.3);
    16.     Debug.Log(i);
    17.     if (i <= 1.0)
    18.     {
    19.         if (i == 1.0)
    20.         {
    21.             state = 1;
    22.         }
    23.     }
    24. }
     
  2. Tom163

    Tom163

    Joined:
    Nov 30, 2007
    Posts:
    1,290
    don't use Time.time? That value constantly increases through the scene, so after the first second, it will always be > 1.0

    Code (csharp):
    1.  
    2. var timer:float = 0.0;
    3.  
    4. function Update() {
    5.    timer += time.deltaTime * 0.3;
    6. }
    7.  
    should do the trick, and you can reset it by a simple "timer = 0.0;"
     
  3. bdev

    bdev

    Joined:
    Jan 4, 2011
    Posts:
    656
    If your trying to have it loop from zero to one repeatedly you'd want to change line:
    Code (csharp):
    1. var i:float = Mathf.Clamp01(Time.time*0.3);
    to
    Code (csharp):
    1. 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:
    Code (csharp):
    1. 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.
     
    CalebMcKinney likes this.