Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

loop executes even when condition is not met

Discussion in 'Scripting' started by pezz, Jun 3, 2014.

  1. pezz

    pezz

    Joined:
    Apr 29, 2011
    Posts:
    606
    The loop below is frustrating me by executing while the conditions are not met.

    Is this a bug? It keeps printing even though I clearly set value to zero.

    Code (JavaScript):
    1. function Update()
    2.  
    3. {
    4.  
    5. if(value !=0)
    6.  
    7. {
    8.  
    9. if (rigidbody.IsSleeping())
    10.  
    11. {
    12.  
    13.                     print("Sleeping");
    14.  
    15.                     print ("last value is" + value);
    16.  
    17. }
    18.  
    19. }
    20.  
    21. value = 0;
    22.  
    23.  
    24. }
     
  2. KulestarUK

    KulestarUK

    Joined:
    Aug 16, 2013
    Posts:
    269
    What does your "value" field start on? It also may depend on if anything else is changing your value field too.

    If it starts on something non-zero and isn't changed by anything else (e.g. nothing else does value=2; for example) then the above should run exactly once :)
     
  3. pezz

    pezz

    Joined:
    Apr 29, 2011
    Posts:
    606
    it starts out > 0.

    And as shown in update I set it to zero and it still runs what is in the if loop.
     
  4. pezz

    pezz

    Joined:
    Apr 29, 2011
    Posts:
    606
    you could try it in a scene and see.
     
  5. KulestarUK

    KulestarUK

    Joined:
    Aug 16, 2013
    Posts:
    269
    It runs just once for me :) What type is your "value" variable? Also you could pop up your script in the inspector to see what value is whilst it plays (as you're possibly setting it from somewhere else).

    Alternatively you might be destroying and recreating the object that your script is attached to - that would cause it to act like its being reset.
     
  6. pezz

    pezz

    Joined:
    Apr 29, 2011
    Posts:
    606

    Lol really?

    I have a print in the if loop that constantly say value is 0.
     
  7. KulestarUK

    KulestarUK

    Joined:
    Aug 16, 2013
    Posts:
    269
    Can you share your whole script/ any more of it? :)
     
  8. pezz

    pezz

    Joined:
    Apr 29, 2011
    Posts:
    606

    Cant share that :D... Kinda private property.

    But you are right. I tried in another scene and it worked.

    So there is something I need to fix.