Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Discussion Simple framerate independent method

Discussion in 'Scripting' started by Johnbaljian, Jan 11, 2023.

  1. Johnbaljian

    Johnbaljian

    Joined:
    Jun 23, 2016
    Posts:
    42
    Can this be considered a simple yet effective framerate independent method ?

    Code (CSharp):
    1.  
    2. void Update()
    3. {
    4.  
    5.         if (Time.deltaTime < SPECIFIC_AMOUNT_OF_FIXED_TIME) return;
    6.  
    7. }
     
  2. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,091
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    Absolutely not.

    What if you never get a frame that takes longer than your interval? Your Update() would always early-out return.

    Instead, set the framerate you want using the Unity API, or else keep a
    float timeElapsed;
    variable and steadily increase it by Time.deltaTime each frame.

    Then check that variable, and when it exceeds your interval, subtract your interval (DO NOT ZERO the variable!) and do one update.