Search Unity

How do i make an int limit?!

Discussion in 'Getting Started' started by N0ova, Nov 18, 2019.

  1. N0ova

    N0ova

    Joined:
    Apr 23, 2019
    Posts:
    3
    I have a charge meter that's set to a max of 150, when i get to that number i want it to stop at 150 in the inspector rather than adding up to infinite
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    upload_2019-11-18_23-20-17.png

    Code (CSharp):
    1.  
    2. using UnityEngine ;
    3.  
    4. public class SunFollower : MonoBehaviour
    5.     {
    6.         [Range ( 0, 150)]
    7.         public float f ;
    8. }
     
  3. N0ova

    N0ova

    Joined:
    Apr 23, 2019
    Posts:
    3
    Nope that didnt work its still going up over the limit, i had it set up like this,
    i dont want to do >= 150 i want it exactly to stop at 150
    Code (CSharp):
    1.         public int chargemeter
    2.  
    3.  
    4.  
    5.         if (Input.GetMouseButton(0))
    6.         {
    7.             //Adding 1 every frame
    8.             ChargeMeter += 1;
    9.         }
    10.      
    11.         if(ChargeMeter == 150)
    12.         {
    13.             Destroy(gameObject);
    14.         }
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    What was suggested above stops you from setting the value higher than 150 in the inspector. What you're doing is setting it higher in code, so just check in code whether you should add more or not.

    Code (CSharp):
    1.         public int chargemeter
    2.  
    3.  
    4.  
    5.         if (Input.GetMouseButton(0))
    6.         {
    7.             //Adding 1 every frame
    8.             if (ChargeMeter < 150)
    9.             {
    10.                 ChargeMeter += 1;
    11.             }
    12.         }
    13.    
    14.         if(ChargeMeter == 150)
    15.         {
    16.             Destroy(gameObject);
    17.         }
     
    Antypodish and N0ova like this.
  5. N0ova

    N0ova

    Joined:
    Apr 23, 2019
    Posts:
    3
    It worked i didn't know i was this close to what i wanted Thank you so much :-D
     
    Joe-Censored likes this.
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    Just in addition for such scenario, also an alternative is to use Clamp, like
    Code (CSharp):
    1. ChargeMeter += 1;
    2. ChargeMeter = Mathf.Clamp ( ChargeMeter, 0, 150 ) ;
    But is probably less optimal for given case.
     
    N0ova likes this.