Search Unity

  1. Unity 2018.3 is now released.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Our response to Improbable’s blog post (and why you can keep working on your SpatialOS game). Read more here
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice

The truth about FixedUpdate()

Discussion in 'Scripting' started by gregzo, Mar 1, 2014.

  1. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    I've lately come across a few posts and questions about FixedUpdate, more specifically about using FixedUpdate() at very high frequency to have a more responsive game loop / time things more precisely.

    This results from a misunderstanding of the docs, which are somewhat ambiguous:

    MonoBehaviour.FixedUpdate()
    Description
    This function is called every fixed framerate frame


    The truth is that FixedUpdate does not run at it's own frequency. It is simply updated many times if needed right before Update, right after Time.fixedTime is, letting code in FixedUpdate pretend it runs at that fixed frequency.

    Simply run the following code at a very low fixed time step to see what I mean:

    Code (csharp):
    1. void FixedUpdate()
    2. {
    3.       Debug.Log( "FixedUpdate realTime: "+Time.realtimeSinceStartup);
    4. }
    5.  
    6. void Update()
    7. {
    8.      Debug.Log( "Update realTime: "+Time.realtimeSinceStartup );
    9. }
    You'll notice FixedUpdate being called a bunch of times in a row right before Update, and then a gap.

    Except for the audio thread, everything in unity is done in the main thread if you don't explicitly start a thread of your own. FixedUpdate runs on the very same thread, at the same interval as Update, except it makes up for lost time and simulates a fixed time step.

    Bottom line: using FixedUpdate for anything else than physics is in the vast majority of cases simply misguided. If you need to call a function a bunch of times because it's late to the party, call it a bunch of times from update or a coroutine, don't let fixedTime fool you into believing it's called at fixed time steps. Plus increasing fixedStep will increase the cpu load that all your physics code generates, potentially nastily decreasing performance.

    The docs for execution order of event functions sum it up nicely:

    So in conclusion, this is the execution order for any given script:
    All Awake calls
    All Start Calls
    while (stepping towards variable delta time)
    All FixedUpdate functions

    Physics simulation
    OnEnter/Exit/Stay trigger functions
    OnEnter/Exit/Stay collision functions
    Rigidbody interpolation applies transform.position and rotation
    OnMouseDown/OnMouseUp etc. events
    All Update functions


    Gregzo
     
    Last edited: Mar 1, 2014
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    31,917
    Yeah, I've been saying that repeatedly for years....

    --Eric
     
  3. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    I think the docs on FixedUpdate itself should be more clear about that. If one digs enough, it's apparent, but just by reading that page one could get the impression that FixedUpdate runs at it's own frequency. The page for Time.fixedTime doesn't help much neither...
     
    plmx likes this.
  4. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,294
    I think you're looking at this backwards. FixedUpdate is supposed to happen less often than Update. FixedUpdate tries to happen at 60fps if I recall, while your Update call happens at whatever your actual framerate is. If you turn off VSync and make a simple scene, you'll see Update gets called many times in between each call to FixedUpdate; that's the intention. If you're getting multiple FixedUpdate calls in between each Update, that means your framerate is really low, and FixedUpdate is trying to make up for that by running multiple times in a row to try and fix the physics. This is "bad" though and not supposed to be the normal state of the game. Running multiple fixed updates to fix broken physics is only supposed to happen occassionally when your frame rate dips; it shouldn't be happening constantly.
     
  5. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,294
    To me, the docs were pretty clear about how it works. It sounds like you're maybe saying that people think if you cram an hour's worth of computation into FixedUpdate, it will magically make it happen in .016 seconds because it's supposed to be "fixed" at 60FPS, but I've seen enough episodes of Doctor Who to know that time doesn't work like that. It makes sense that if you force it to do more than .016 seconds worth of work, it's going to have to play catch-up.
     
  6. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    Hi,

    I'm reacting specifically to posts I've seen where users where setting a very small fixedStep to try to get a higher time precision - fixedStep of .005 to get 200 FixedUpdate() calls a second, for example. For less experienced devs, it's easy to misunderstand the docs and to believe FixedUpdate will actually run at a 1/fixedStep frequency. In my opinion, the docs should clearly state that FixedUpdate is called just before Update, whatever the fixed step. It is only the number of times FixedUpdate will be called that changes when adjusting fixedStep, not it's actual real time update rate. Still seeing users getting misled by this, so I figure the docs could be more explicit.
     
  7. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,294
    Yeah I guess that makes sense. It would make sense to do that if your framerate is really high and you want physics to be a little more precise, but purposefully trying to make FixedUpdate happen more often than Update kind of defeats the whole point of it.
     
  8. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    Agreed. The main point I think should get across to every Unity beginner is that Unity's game loopp runs on a single thread, and that wherever you place your method calls, wether in Update, LateUpdate, Coroutines or FixedUpdate, they won't be called at a different frequency - except for OnAudioFilterRead, which runs on a different thread, the rate of which is dependent on audio buffer size and output sampling rate.
     
  9. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,294
    Well, FixedUpdate does get called at a different frequency as long as your frame rate is higher than the fixed step (60 FPS i think). If you're running at 180FPS, you will get three Update calls in between each FixedUpdate call.
     
  10. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    Yep, FixedUpdate can skip frames, but that doesn't make it frame rate independent. The point is : same thread, no benefits in using it for anything else than what it's meant for - Physics. Wether it skips a frame or gets called multiple times during one doesn't change that it does not run at a frequency independent of that of Update().

    My! We're finicking!
     
  11. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,294
    I imagine it's basically like this:

    Code (csharp):
    1.  
    2. float timer = 0;
    3. while(true)
    4. {
    5.      while(timer > fixedStep)
    6.     {
    7.          FixedUpdate();
    8.          timer -= fixedStep;
    9.      }
    10.      Update();
    11.      timer += deltaTime;
    12. }
     
    Time-Jockey and voidscripter like this.
  12. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,294
    To me, it would make sense to put anything that doesn't need to be updated quickly in there and set a lower fixed step. So you could do pathfinding or AI in FixedUpdate, and it might improve your framerate since it wouldn't have to compute as often. But again, this is assuming your framerate is higher than the fixed step. Doing it backwards (making it compute more often than your framerate) doesn't make any sense; it just slows down your framerate.
     
  13. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    31,917
    50. The default fixed timestep is .02, and 1/.02 = 50.

    No, that's a bad idea. FixedUpdate is tied specifically to physics and should only be used for physics. There are plenty of other ways to do "update every so often" that are much more appropriate and give you more control...coroutines, InvokeRepeating, threads.

    --Eric
     
    mhogan256 and Trexug like this.
  14. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,371
    Also work the other way around... On a game running at 30 FPS, you get more FixedUpdate than Update.
    We found having out control code in there - for our 30-40FPS mobile games - to get better/more responsive control.

    We also found that FixedUpdate - if not handled properly - can destroy your framerate. Let's say FixedUpdate is unable to perform its task under the 0.02s delta, the next frame it will try to put 2 update... and since it fails again, the next will try to push 3, etc. Of course, that should never happened, and we quickly found out why and removed the faulty code.
     
  15. cowlinator

    cowlinator

    Joined:
    Mar 15, 2012
    Posts:
    69
    I do not notice this; I notice the opposite.

    While running this test script:
    Code (csharp):
    1.    double dspSamplesStart = double.NaN;
    2.  
    3.    void Update()
    4.    {
    5.      timerSamplesCheck_Upd();
    6.    }
    7.  
    8.    void FixedUpdate()
    9.    {
    10.      timerSamplesCheck_Fx_Upd();
    11.    }
    12.  
    13.    void timerSamplesCheck_Fx_Upd()
    14.    {
    15.      if(double.IsNaN(dspSamplesStart))
    16.        dspSamplesStart = AudioSettings.dspTime;
    17.  
    18.      double time = Time.time;
    19.      double fTime = Time.fixedTime;
    20.      double realTime = Time.realtimeSinceStartup;
    21.      double sTime = AudioSettings.dspTime - dspSamplesStart;
    22.      Debug.Log("FixedUpdate: t: " + time + ", ft: " + fTime + ", rt: " + realTime + ", st: " + sTime);
    23.    }
    24.  
    25.    void timerSamplesCheck_Upd()
    26.    {
    27.      if(double.IsNaN(dspSamplesStart))
    28.        dspSamplesStart = AudioSettings.dspTime;
    29.  
    30.      double time = Time.time;
    31.      double fTime = Time.fixedTime;
    32.      double realTime = Time.realtimeSinceStartup;
    33.      double sTime = AudioSettings.dspTime - dspSamplesStart;
    34.      Debug.LogWarning("Update: t: " + time + ", ft: " + fTime + ", rt: " + realTime + ", st: " + sTime);
    35.    }
    36.  
    I get the result:
    FixedUpdate: t: 0, ft: 0, rt: 0.041592188179493, st: 0
    Update: t: 0, ft: 0, rt: 0.0533649511635304, st: 0
    FixedUpdate: t: 0.00499999988824129, ft: 0.00499999988824129, rt: 0.0570647902786732, st: 0
    FixedUpdate: t: 0.00999999977648258, ft: 0.00999999977648258, rt: 0.0597184114158154, st: 0.021333333333132
    FixedUpdate: t: 0.0149999996647239, ft: 0.0149999996647239, rt: 0.0620354078710079, st: 0.021333333333132
    FixedUpdate: t: 0.0199999995529652, ft: 0.0199999995529652, rt: 0.0643015056848526, st: 0.021333333333132
    Update: t: 0.0199999995529652, ft: 0.0199999995529652, rt: 0.0666103810071945, st: 0.021333333333132
    FixedUpdate: t: 0.0249999985098839, ft: 0.0249999985098839, rt: 0.235997170209885, st: 0.192000000000007
    FixedUpdate: t: 0.0299999993294477, ft: 0.0299999993294477, rt: 0.23847071826458, st: 0.192000000000007
    FixedUpdate: t: 0.0350000001490116, ft: 0.0350000001490116, rt: 0.240717142820358, st: 0.192000000000007
    FixedUpdate: t: 0.0399999991059303, ft: 0.0399999991059303, rt: 0.242956295609474, st: 0.192000000000007
    FixedUpdate: t: 0.044999998062849, ft: 0.044999998062849, rt: 0.245275855064392, st: 0.192000000000007
    FixedUpdate: t: 0.0499999970197678, ft: 0.0499999970197678, rt: 0.247482508420944, st: 0.192000000000007
    FixedUpdate: t: 0.0549999997019768, ft: 0.0549999997019768, rt: 0.249757155776024, st: 0.213333333333139
    FixedUpdate: t: 0.0599999986588955, ft: 0.0599999986588955, rt: 0.25208654999733, st: 0.213333333333139
    FixedUpdate: t: 0.0649999976158142, ft: 0.0649999976158142, rt: 0.25441637635231, st: 0.213333333333139
    ...
    FixedUpdate: t: 0.194999992847443, ft: 0.194999992847443, rt: 0.312763512134552, st: 0.277333333333218
    Update: t: 0.198654785752296, ft: 0.194999992847443, rt: 0.315083056688309, st: 0.277333333333218
    FixedUpdate: t: 0.199999988079071, ft: 0.199999988079071, rt: 0.340063631534576, st: 0.298666666666577
    FixedUpdate: t: 0.204999998211861, ft: 0.204999998211861, rt: 0.342683017253876, st: 0.298666666666577
    ...
    ...
    ...
    Update: t: 2.92386531829834, ft: 2.91999983787537, rt: 2.9623339176178, st: 2.9226666666666
    FixedUpdate: t: 2.92499995231628, ft: 2.92499995231628, rt: 2.96535205841064, st: 2.9226666666666
    Update: t: 2.92937564849854, ft: 2.92499995231628, rt: 2.96794056892395, st: 2.9226666666666
    FixedUpdate: t: 2.92999982833862, ft: 2.92999982833862, rt: 2.97126793861389, st: 2.9226666666666
    FixedUpdate: t: 2.93499994277954, ft: 2.93499994277954, rt: 2.97814989089966, st: 2.9226666666666
    Update: t: 2.93528437614441, ft: 2.93499994277954, rt: 2.98049831390381, st: 2.94399999999996
    FixedUpdate: t: 2.93999981880188, ft: 2.93999981880188, rt: 2.98562502861023, st: 2.94399999999996
    FixedUpdate: t: 2.9449999332428, ft: 2.9449999332428, rt: 2.98832273483276, st: 2.94399999999996
    Update: t: 2.9496214389801, ft: 2.9449999332428, rt: 2.99067115783691, st: 2.94399999999996

    Ellipses represent omissions.
    Most of the time, all time variables update, and fixedTime definitely seems to update at regular intervals (mostly).
    The only time variable that seems to not be very good at updating every FixedUpdate() is AudioSettings.dpsTime.
    Ran in Unity Editor 4.6.1f1, Windows 7 x64, fixed timestep 0.005, Max timestep 0.3333333

    Edit: I removed one line from the result log I posted because I realized it was a duplicate (I'm still looking at the actual log).
     
    Last edited: Feb 1, 2015
  16. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    Just log a delta of realtimeSinceStartup from FixedUpdate, and you'll see what I mean. Does it correspond to fixedDeltaTime? Nope...
     
    Kiwasi likes this.
  17. Nubz

    Nubz

    Joined:
    Sep 22, 2012
    Posts:
    553
    Never heard of a lot of this.
    Somewhere I was told when I started that FixedUpdate was for physics so that's all I ever did inside it lol.
    Good info to know regardless.
     
    Kiwasi likes this.
  18. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,057
    This comes as no surprise to anyone who read the docs.

    http://docs.unity3d.com/Manual/ExecutionOrder.html

    This is the key reason that FixedUpdate is for physics, and anything that needs to be synced to the physics loop.

    As usual for Unity execution is linear. Nothing is ever truest simoltaneous. And very few things use their own thread.
     
    Iron-Warrior likes this.
  19. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,057
    This all depends if your game is more dependent on physics or rendering. I've built simulations where physics fidelity is far more important then rendering speed. FixedUpdate is meant to run at a constant time step. Speed relitive to rendering is irrelevant.
     
  20. youyouzizi

    youyouzizi

    Joined:
    Oct 30, 2014
    Posts:
    3
    I want to use FixedUpdate() at very high frequency to have a more responsive game loop and then find this page...I try InvokeRepeating and it's the same as FixedUpdate. How can I have a more responsive game loop?
     
  21. pws-devs

    pws-devs

    Joined:
    Feb 2, 2015
    Posts:
    59
    I would suggest that you look at what is running in your game loop to 'clean up' what is hogging computational time. If you have already optimized you game loop for performance and is really running out of options, then just use System.Timers to simulate your more responsive game loop as System.Timers starts a timer in a different thread to count the actual time...
     
  22. youyouzizi

    youyouzizi

    Joined:
    Oct 30, 2014
    Posts:
    3
    You mean put my game loop in a different thread? I will try put parts of my scripts in a different thread, like input scripts.
     
  23. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    won't help and will be very tough to implement. Most methods of the UnityEngine namespace simply CANNOT be called from anywhere else than the main thread. Threading in Unity can be useful in certain specific use cases, such as AI or I/O, but in your case, look elsewhere first.

    What frame rate are you achieving? Is it stable? Any GC spikes? What do you mean by unresponsive, on what platform? Etc...
     
  24. youyouzizi

    youyouzizi

    Joined:
    Oct 30, 2014
    Posts:
    3
    I just try put my input code in a different thread and use a timer using sleep to improve input responsive.
     
  25. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,057
    Of all the things to multi thread and run at a different rate to rendering, input is not one of them.
     
    gregzo likes this.
  26. gregzo

    gregzo

    Joined:
    Dec 17, 2011
    Posts:
    795
    Amen.
     
  27. pws-devs

    pws-devs

    Joined:
    Feb 2, 2015
    Posts:
    59
    The fact that you actually jumped the gun by really using another thread to do input handling. *facepalm*.

    Here's a better suggestion. Instead of processing logic for your input directly, try batching them into a queue and then use the other thread to process the actual logic that you want to perform for that inputs batched, this way, you would have lesser issues with crazy input logic occuring.

    The possible reasons that your inputs are not as responsive might be due to bulk logic that is dependent on your input. Keep in mind that calling an external function in the frame just executes that function in the same frame. So if you did something like

    if(Input.GetKey(Keycode.K))
    {
    ExecuteBulkLogic();
    }

    It's definitely going to hog the computational time.
     
    akingdom, AnomalusUndrdog and Kiwasi like this.
  28. Ferb

    Ferb

    Joined:
    Jan 4, 2014
    Posts:
    20
    I would say that FixedUpdate isn't necessarily just for physics - surely it's for anything that the gameplay depends on, which will be mainly physics, but might include a few other kinds of computation as well. Sometimes my fixedupdates have taken about a second when rearranging a level, it does start trying to fit loads of fixedupdates in between every Update then until its paid off the deficit. I'm planning to put a level transition screen in place while that's happening to hide the fact nothing's moving, and reduce Time.timeScale during the one long fixedUpdate so at least Unity doesn't feel guilty about it and make the framerate bad for a second or two afterwards trying to make up for having just missed 25 fixedupdates.

    While speaking of using another thread, I've read that you can use threads in Unity, but does this really carry across all the different platforms that Unity compiles to? Surely there will be trouble if you write something using multithreading and try to compile to WebGL, won't there? Or does the compiler have some way of handling that?
     
    Last edited: Apr 6, 2015
  29. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    31,917
    No, it's physics...it's specifically and exclusively the timer physics runs on, and is subject to all the rules about physics. While nothing is explicitly preventing you from using FixedUpdate for other things, I can't think how it would be a good idea.

    Almost all.

    At this time, yes.

    No.

    --Eric
     
    djfunkey and pws-devs like this.
  30. kebrus

    kebrus

    Joined:
    Oct 10, 2011
    Posts:
    413
    But using it for others things is technically bad? or are you saying it's a bad design decision and therefore most of the times it slows you down?

    I have this situation where I'm running some logic AI in fixed updated exactly because I need to do some physic stuff, putting that logic outside it and trying to sync with it would be a tremendous effort, using it inside is predictable, I know exactly how each force is affecting the object and I can work with them seamlessly
     
  31. TomasRiker

    TomasRiker

    Joined:
    Jan 26, 2012
    Posts:
    39
    It should be mentioned that putting logic-relevant code into Update rather than into FixedUpdate might lead to non-repeatable results. For instance, imagine you're doing AI computations in there. When the framerate is high, the AI will be able to "think" more or react more quickly than when the framerate is low. You have to decide for yourself if that's acceptable - for me it's not.

    Of course, you could also simulate your own FixedUpdate that runs at whatever "frequency" you like (not having to use the same frequency as physics) by calling it from within Update, just like Unity does with FixedUpdate. Basically you have to accumulate elapsed realtime and whenever it is greater than your target interval (e.g. 20 ms for 50 Hz), call your method, possibly multiple times in a row. That's what I've been doing before I started using Unity.

    As LightStriker said, you have to make sure that your target machine can actually handle all the things you do in FixedUpdate within the alloted time, otherwise you run into trouble. You'd either have to let the game run more slowly, which is not always possible (multiplayer games, for example) or give up the idea of repeatable results.
     
    Last edited: May 23, 2015
  32. whisp

    whisp

    Joined:
    Jun 21, 2014
    Posts:
    3
    ThomasRiker is right.

    But you don't even run into trouble if fixedupdate doesn't manage to keep up with it's default 50 per second. You must not use deltatime in fixed update, instead you should consider 1 fixedupdate as a fixed time unit

    E.g., let's say you have an evolution simulation game where 1 fixedupdate is 1.2 of your gameworld minutes, thus you'll have 60 minutes gameworld-time per real second. If fixedupdate can't keep up, it will run less often than 50 times per second. The worst that will happen is that your game will run slower, e.g. only 30 game minutes per second at 25 fixedupdates per second. Fixedupdate guarantees that it will never run more often than 50 times per second, even if there was a long lag before.

    Edit: According to BoredMormon, Time.deltaTime also returns a fixed value within FixedUpdate. In that case it is safe as well.

    You can test this yourself: Setup a scene with a sphere, add a rigid body to it and make sure gravity is enabled for the rigid body. Setup a script where you do something very computing intensive in the fixedupdate(), maybe after a second, when the sphere already fell down a bit. Make sure the calculation takes a couple of seconds and runs only 1 time. (E.g. calculate the faculty of 2 billions 2-3 times). You will notice how the sphere stops while your calculation runs, and after several seconds, when the calculation is done, the sphere will not make up for the lag, instead it will continue falling from where it was before the calculation.

    Only in Update you have to rely on deltatime. And it is very prone to lag. While a 10 minutes lag would be no problem with the fixedupdate, imagine what would happen with your game with Update, if deltatime is 600 seconds. (Allowedly, a 10 minutes lag is not usual. :) )
     
    Last edited: Aug 22, 2015
  33. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,057
    Rubbish. Time.deltaTime will return the fixed time step within FixedUpdate. It's perfectly appropriate to use.
     
  34. whisp

    whisp

    Joined:
    Jun 21, 2014
    Posts:
    3
    In that case it is indeed perfectly approperiate to use. I've edited my post.
     
    Kiwasi likes this.
  35. LaJean

    LaJean

    Joined:
    Sep 6, 2015
    Posts:
    10
    Guys, let's see if I can pinpoint some facts correctly:
    1. FixedUpdate() runs not necessarily at a fixed tick but it tries a constant runs/second. It can't run faster that specified Time.fixedTime but it can run slower.
    2. I can't see any reason not to use it for custom "tick" events instead of using Time.deltaTime in Update() to regulate the events.
     
  36. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    6,078
    That depends on what you mean by a 'fixed tick'...

    It is fixed, in that the simulated time difference is fixed. The REAL WORLD difference is NOT fixed. It can run faster or slower, as its not a 'real world' time difference.

    Basically every time the engine goes to update the physics simulation, it determines the amount of time that has passed. This is X seconds. It then determines the number of times physics should have calculated during that time... X / fixedDeltaTime. It will then call FixedUpdate that many times to update the simulation to the state it aught to be in at that point. Note this 'X' seconds that passed is not 'unscaledTime', but rather the game time. This is why it's effected by Time.timeScale. You can see this by setting Time.timeScale to like 10, or 20, and you'll see that FixedUpdate is called 10 or 20 times between each Update call... yet the deltaTime returned is STILL the same fixed value.

    This works because Physics simulations are supposed to be deterministic. You can update the simulation by its time step at ANY time... if you updated it by 1/50th of a second in simulation time, every 1 second of real time, you'd get a simulation running at 1/50th that of real time. Either way, the resulting 'steps' between FixedUpdates are all deterministic.

    As a result if the framerate drops low, FixedUpdate may process multiple times in a row to catch up for the lost time. Or if the framerate is running really high, FixedUpdate may be skipped relative to Update. The actual time between calls may be micro seconds (called multiple times in a row), or entire seconds (the first call of this frame since last frame in a low framerate setting), you never know. And it doesn't matter... because simulation wise, it's that fixed time later.

    So, really, FixedUpdate does NOT reflect real world time change! Any of its time values (delta, or total) should be considered relative ONLY to the physics simulation. And therefore its useless for anything BUT physics simulation.

    I don't even know what a "custom tick event" is to even say. If you're talking about an event that is relative to physics simulation, sure, it's totally legit. Otherwise... no.
     
    Last edited: Sep 6, 2015
    Marrt and Kiwasi like this.
  37. LaJean

    LaJean

    Joined:
    Sep 6, 2015
    Posts:
    10
    By "custom tick event" I mean any event i.e. stroboscope light flashing, health drop in damage over time, stopwatch count, you name it, that is supposed to happen regularly, at a tick rate. These are not related to Unity physics. In fact, anything you could find the need to use delta timing for. So if somebody has an itch for delta timing, just drop Time.deltaTime altogether and use FixedUpdate(). Right?
    And in the last post I emphasized one point that it's very easily overlooked and TBH I'm not sure I got it right:
    FixedUpdate() will lag behind and will not compensate for high lag if it has to run faster than Time.fixedTime; I don't know whether it has a slow limit though but I suppose not.
     
  38. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    6,209
    I try not to think about it.

    When I break something because of this, I'll consider thinking about it..... Hopefully that doesn't happen o_O ..
     
  39. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    31,917
    No, FixedUpdate is specifically tied to the physics framerate, and should definitely only be used for physics. See the first post in this thread. In addition to the reasons listed there, if you abuse FixedUpdate for other things, and later decide that you need to increase/decrease the physics framerate, your non-physics FixedUpdate code is now borked.

    --Eric
     
    Marrt likes this.
  40. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    6,073
    As an additional note, it's trivially easy to create your own FixedUpdate-style updating code. You can use whatever update interval you want and have as many of these as you want. It boils down to:
    Code (csharp):
    1. public float updateInterval = 0.02f;
    2. private float lastUpdated = 0f;
    3. void Start() {
    4. lastUpdated = Time.time;
    5. }
    6. void Update() {
    7. while (lastUpdated < Time.time) {
    8. lastUpdated += updateInterval;
    9. MyCustomFixedUpdate();
    10. }
    11. }
    It's not much harder if you want to add logic to send out a message or pass the update time as a parameter to MyCustomFixedUpdate.

    ...and none of this will ever be affected by changes in physics!
     
    AnomalusUndrdog likes this.
  41. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,057
    If you do this a lot you should consider a coroutine or invoke repeating.
     
  42. LaJean

    LaJean

    Joined:
    Sep 6, 2015
    Posts:
    10
    I get it, thanks guys. Still IMHO a coroutine is neater than custom code.
     
  43. RElam

    RElam

    Joined:
    Nov 16, 2009
    Posts:
    375
    Ultimately this is quite subjective, but my suggestion is the opposite. Although on a technical level you are correct, physics is also where everything moves, and in many games, that makes it highly tied to alot of other logic. The main reason most physics simulation systems use a fixed timestep is because it avoids artifacts caused by using a variable timestep, and the inconsistency that causes those artifacts will cause artifacts in other code using a variable timestep (mentioned by TomasRiker earlier in thread). IMO, FixedUpdate should be considered your de facto game logic function, and if you want to run something less frequently, then skip frames, and if you need changes that are non-physics related (like 1:1 FPS camera movement) then do that in Update.

    Too much focus, IMO, is given here to when things are run with relation to real time, what's important is that it is designed to run in a fixed time with relation to 'game time', and that's quite valuable for games where more deterministic nature is desired. Most games can use a fixed timestep of 30 with interpolation, put game logic in FixedUpdate, and be better off in the end.
     
  44. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    31,917
    Only if you're using physics, which a lot of games don't. Also, read the first post in this thread.

    --Eric
     
  45. RElam

    RElam

    Joined:
    Nov 16, 2009
    Posts:
    375
    Yea, I read it, not sure what you think I missed. I don't disagree with any specific fact presented, just the conclusion that FixedUpdate should be considered 'physics only'. Even without physics, as stated there is value to FixedUpdate, and perhaps good reason it's not called PhysicsUpdate/PrePhysicsSimulation or something like that.
     
  46. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    31,917
    Well, this part: "don't let fixedTime fool you into believing it's called at fixed time steps". I wouldn't be surprised if they'd rather have called it PhysicsUpdate in hindsight.

    --Eric
     
  47. RElam

    RElam

    Joined:
    Nov 16, 2009
    Posts:
    375
    It's only confusing to those that confuse game time with real time, and I was responding to conclusions like yours that it should only be used for physics. Pretty much all unity time values are in game time, and AFAIK it makes no guarantees about when something is run with regards to real time or if it's threaded (as a high level engine, it shouldn't). Just because some people might have made erroneous assumptions that FixedUpdate runs at a fixed realtime interval doesn't devalue it's general use.

    And take a look at the docs on time, they speak of physics and other fixed updates like FixedUpdate... all indications are that they understand the value of FixedUpdate as a standalone concept. Perhaps you feel that LateUpdate should be called PreRenderUpdate or something, but I think it's smart to name high level updates as such, not give them the names of the largest subsystem they're updating for.
     
  48. UltimateWalrus

    UltimateWalrus

    Joined:
    Jul 19, 2014
    Posts:
    10
    I found this FixedUpdate behavior in my own tests, so I was glad to see this post to confirm it.

    Even knowing about this behavior, I can confidently assert that there is nothing wrong with updating your game world in FixedUpdate; in fact if you want your game to be deterministic, it's a necessity. Time.fixedDeltaTime is a constant value from call to call, so as long as you only use that as your delta, you'll be fine.

    There are very good reasons for wanting to run your game on a fixed timestep, though it isn't totally possible in Unity due to sporadic calling of FixedUpdate, which messes up our ability to get input at regular intervals. I summarized this in another thread; I'll post it here as well:

    Look at it this way: suppose I'm playing a bullet hell shooter requiring very small adjustments to the player position. I hold the "right" key for 1/30 of a second, which, when the game is running at 60fps, would move me 2 pixels to the right, let's say. However, right at that moment, the framerate stutters to 15fps. This means I can't get another Update() and can't poll Input to see the key is up until 1/15 of a second after I started holding down the key. Unity will now think the key is held down for 1/15 of a second, and move 4 pixels instead of the 2 pixels it really should have moved.

    This is how Unity works normally, even if you use variable timestep like you're "supposed to." A home-rolled engine running on a proper fixed timestep would be able to handle this scenario correctly.

    If you are a AAA developer looking to squeeze out every last bit of performance, then I'll admit variable timestep makes sense. However it's totally inappropriate for twitch-based games that are supposed to react deterministically to player input even between frame stutters (fighting games, bullet hells, action games, etc.). I feel many variable timestep preachers need to stop and think about why Unity has to run its physics on a fixed timestep in the first place: because it must be deterministic and not suddenly glitch out when the framerate gets low.
     
    metroid085 and Marrt like this.
  49. Garth-Smith

    Garth-Smith

    Joined:
    Apr 26, 2012
    Posts:
    1,237
    Last edited: Dec 30, 2015
  50. UltimateWalrus

    UltimateWalrus

    Joined:
    Jul 19, 2014
    Posts:
    10
    Those are some great resources!

    By the way, I didn't mean to say there's any harm in using Update() for purely cosmetic effect code; it can save you some CPU if you only update things like particle effects when they absolutely have to be, which would be on the variable timestep.

    However, I used FixedUpdate for all my gameplay logic, and my games are better for it, for reasons that have been discussed over and over. The only caveat is that, because of the FixedUpdate queuing that gregzo described, Input fidelity will drop as the framerate does too. This is solved trivially in a home-rolled engine but in Unity we are basically stuck just making sure the framerate doesn't drop below 60 if we want to preserve Input fidelity.

    I have a feeling I and gregzo may be on the same page here, and it's just that what I call "gameplay" he calls "physics." I rarely make physics-based games so I tend to think of physics more as something to use for cosmetic purposes. Someone who only makes physics-based games might consider all gameplay code to be physics-related.