Search Unity

Avoid negative integers in my count down script

Discussion in 'Editor & General Support' started by shabazzster, Jul 20, 2011.

  1. shabazzster

    shabazzster

    Joined:
    Mar 17, 2010
    Posts:
    104
    How do i prevent the script from falling into the negative integers when counting down?
    When i press the button (seal) the number of carts is deducted by 1. However, if I keep pressing the seal button,
    The number of carts goes into the negative integers. How do I prevent this, and keep the number of carts from going into the negative integers?



    Code (csharp):
    1.  
    2.  
    3. public int carts;
    4.  
    5. void OnGUI()
    6.  
    7. {
    8.  
    9. GUI.Label(new Rect (30,107,100,20),"Carts");
    10.  
    11.  
    12. if(GUI.Button(new Rect (87,210,115,30),"seal"))
    13.        
    14.     {
    15.        carts -- ;
    16.     }
    17.  
    18. }
    19. /CODE]
    20.  
    21. Thanks
    22. ~K
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Code (csharp):
    1. if (--carts < 0) carts = 0;
    --Eric
     
  3. shabazzster

    shabazzster

    Joined:
    Mar 17, 2010
    Posts:
    104
    Well, Eric5h5 thanks a bunch!

    I had the same wording but l put curly braces around it, which made it work all kinds of wrong (but with no apparent errors).

    Syntax makes and breaks .

    Thanks again Eric
    ~K
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You can still use curly braces (and usually should; in this case it's trivial enough that I didn't bother):

    Code (csharp):
    1. if (--carts < 0) {
    2.     carts = 0;
    3. }
    --Eric