Search Unity

Mathf.clamp

Discussion in 'Scripting' started by martis941, Oct 21, 2016.

  1. martis941

    martis941

    Joined:
    Feb 22, 2016
    Posts:
    95
    what have i done wrong here?
    i want player to be able to use health potion but after using it , player's hp cant be higher than the maximum
    starting health is max health in that case
    Mathf.Clamp((currentPlayerHealth += healthRestored),0,StartingHealth);

    for example player had 3 hp left and after using potion(which retrieves 10 hp) should have 10 hp and instead he have 13.
     
  2. Piflik

    Piflik

    Joined:
    Sep 11, 2011
    Posts:
    293
    Mathf-Clamp returns the clamped value and does not automatically modify the first argument (it actually cannot, since it is not a reference but a value)

    Use it like this:
    Code (CSharp):
    1. currentPlayerHealth = Mathf.Clamp(currentPlayerHealth + healthRestored, 0, StartingHealth);
     
  3. Daerst

    Daerst

    Joined:
    Jun 16, 2016
    Posts:
    275
    What happens here is that Mathf.Clamp returns a clamped result, that is currently discarded because you are not assigning it to any variable. The function does not modify the value 'in place'.

    Code (CSharp):
    1. currentPlayerHealth = Mathf.Clamp(currentPlayerHealth + healthRestored, 0, StartingHealth);
    // EDIT: Sorry I'm late to the party ;-)