Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Mathf.Clamp not working

Discussion in 'Getting Started' started by pod11, Mar 7, 2020.

  1. pod11

    pod11

    Joined:
    Jan 6, 2019
    Posts:
    40
    Could someone explain me why is mathf.clamp not claming value of normalizedValue ?
    I tried using clamp in several ways before asking, but it jsut seems to be not affecting anything.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class HealthBar : MonoBehaviour
    6. {
    7.     public float displayedMaxValue=100;
    8.     public float displayedCurrentValue=100;
    9.  
    10.     private float normalizedValue;
    11.     public Transform bar;
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.  
    16.         displayedCurrentValue = -50;
    17.      
    18.     }
    19.     private void Update()
    20.     {
    21.        
    22.  
    23.         Mathf.Clamp(normalizedValue = displayedCurrentValue / displayedMaxValue, 0, 1);
    24.      
    25.         bar.localScale = new Vector3(normalizedValue,1f,1f);
    26.     }
    27.  
    28. }
     
    Last edited: Mar 7, 2020
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    8,887
    Because you are ignoring its result.

    Also, it's bad form to do an assignment within the argument to a function. Just don't do it.

    Perhaps you meant this?

    Code (csharp):
    1. normalizedValue = Mathf.Clamp(displayedCurrentValue / displayedMaxValue, 0, 1);
     
    Bill_Martini and Ryiah like this.
  3. polemical

    polemical

    Joined:
    Jun 17, 2019
    Posts:
    121
    Code (CSharp):
    1. campos.x = Mathf.Clamp(campos.x, 0, xmax);
    2. campos.z = Mathf.Clamp(campos.z, 0, zmax);
     
unityunity