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.

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,017
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    33,474
    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.