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

Frame By Frame Gives Different Results Than Runtime

Discussion in 'Scripting' started by Sprawl, May 20, 2014.

  1. Sprawl

    Sprawl

    Joined:
    Jan 19, 2014
    Posts:
    42
    I've noticed a strange behaviour in unity recently. With the OnTriggerStay Method, I'm setting a variable to true if there was a collision. Then, If it is true I do something with it and put it back to false.

    While testing I realized that even though the object was always in the Trigger collider, it wasnt getting called all the time. However, When I stop the game and play it frame by frame, It is actually being called each time.

    I really Don't know what could be causing this. There is not noticeable lag, I'm over 60fps all the time.
     
  2. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    My guess:

    Update() and FixedUpdate() run at separate times. Or to put it another way, physics calculations are not sync'd up with frames being drawn on the screen. This means you can have Update() run several times before physics is recalculated and OnTriggerStay() gets called again, or vice versa.

    So I'm guessing you set a bool to true in OnTriggerStay(), set it to false during Update(), and it wasn't set back to true by the following Update() because no physics calculations were performed and OnTriggerStay() was never called again.
     
  3. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    If you are constantly setting a flag true, performing an action, then setting the flag false for each onTriggerStay, couldn't you set the flag true during the OnTriggerEnter, then false upon OnTriggerExit? Then perform the action each frame while the flag is true.

    Not sure the exact thing you are trying to accomplish, but that seems like an easier method that doesn't require physics to sync perfectly each frame.
     
  4. Sprawl

    Sprawl

    Joined:
    Jan 19, 2014
    Posts:
    42
    @Garth
    This is exactly it, Thanks a lot.
    I wasn't aware of the run order of the different methods. Putting the code in Fixed Update fixed the issue.

    @Zaladur, This isn't all i'm doing with it, but I kept it simple for the question since I made sure the other stuff wasn't the issue. Thanks for the answer.
     
  5. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Thanks for that man! It was obvious what your problem was and the subject was even on topic... It's much harder to answer rambling super generic questions that get asked so often.