Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question How to elegantly disable OnTriggerEnter when the scene first loads?

Discussion in 'Physics' started by jakesee, Mar 9, 2024.

  1. jakesee

    jakesee

    Joined:
    Jan 7, 2020
    Posts:
    81
    I have 2 scenes A and B.

    There are many similar GameObjects in Scene A. When two moving GameObjects touches each other, on OnTriggerEnter() is invoked, the game state (including position, velocities etc.) is saved and Scene B is loaded.

    After completing some task in scene B, user is returned to scene A again, which is now loaded with the two GameObjects their the last position (along with all other GameObjects), touching each other as before. Since the two GameObjects spawned in their initial position touching each other in Scene A, I expect OnTriggerEnter() not to be invoked, however, it still does.

    Is there an elegant built-in way to tell OnTriggerEnter not to fire in this state?

    The only hack I can think of now, is to skip a few frames in the beginning before starting the game loop proper, but it's ugly.
     
    Last edited: Mar 9, 2024
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    1,125
    If the objects don't have any velocity in OnTriggerEnter then they must've spawned into their current positions and not moved there and so you can ignore them.
     
  3. jakesee

    jakesee

    Joined:
    Jan 7, 2020
    Posts:
    81
    They will have initial velocities. Basically, the complete state is saved and restored when Scene A is reloaded to continue from where it was before Scene B.
     
  4. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    1,125
    In OnTriggerEnter you can check Time.timeSinceLevelLoad and if it's less than 2 then ignore the objects.
     
    jakesee likes this.
  5. jakesee

    jakesee

    Joined:
    Jan 7, 2020
    Posts:
    81
    Thanks, that's a good suggestion.

    Unfortunately, there are many similar GameObjects in Scene A. In the slim chance that another pair of GameObjects collide within the 2 milliseconds, I would want OnTriggerEnter to fire.

    Maybe I can do something with Time.frameCount, but not really sure how it works at the moment. WIll have to figure.

    EDIT: Testing on a brand new Scene, the OnTriggerEnter is invoked at Time.timeSinceLevelLoad == 0. Not sure whether this is reliable on slow computers?
     
    Last edited: Mar 9, 2024