Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
4
Question by zmar0519 · Apr 21, 2011 at 10:53 PM · updatefixedupdatelateupdate

how to achieve a LateFixedUpdate effect

Hi, everyone, I was just wondering if there was a way to achieve a LateFixedUpdate() function effect, because I am trying to stay with fixed update for my game, and I need a late update function. All help is appreciated!!! :)

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Peter G · Apr 24, 2011 at 12:39 AM 0
Share

I edited my post

5 Replies

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by prime31 · Mar 03, 2014 at 04:06 AM

OP, please unmark the current answer as correct. It is most certainly not correct and folks who come here and read it will get some misinformation.

@Peter G, your understanding of Unity's threading is partially wrong! All physics operations are running in their own thread which you cannot access. Almost the entirety of Unity with regard to managed scripts is indeed running in a single thread. All SendMessages and MonoBehavior callbacks (except for OnAudioFilterRead which runs on the audio thread) will be run in the main thread.

With your code, you are merely firing an event immediately after FixedUpdate. While indeed it will run after FixedUpdate it will not have the desired effect that OP is looking for and it will not mimic the LateUpdate. In fact, anything that happens in your LateTick would work identically if it were just put in FixedUpdate.

Let me explain:

First, Unity will call all the FixedUpdate methods. At some indeterminate time (and this is why your method wont work) Unity will run the physics tick on the physics thread. Eventually the physics tick will complete and all the Transforms that were affected by it will be updated. Your LateTick will have run before the actual physics tick updated the Transforms.

In reality, there is no 100% solid way to pull off a LateFixedUpdate. The closest thing to a LateFixedUpdate would be a collision callback such as OnCollisionStay. The reason for this is that the OnCollision* method will be called on the Unity main thread after the physics tick has run the simulation and moved all the Transforms.

Comment
Add comment · Show 9 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image whydoidoit · Mar 03, 2014 at 04:16 AM 0
Share
  • Furthermore LateFixedUpdate makes no sense in the first place. LateUpdate specifically happens during the phase of rendering an actual frame, just after any animation is applied, that happens irrespective of whether you move an object during physics or not.

If you want to ensure something runs after something else either orchestrate it yourself by using a sequenced list of delegates or calls in a FixedUpdate method or use script execution order.

alt text

avatar image prime31 · Mar 03, 2014 at 04:30 AM 2
Share

@whydoidoit, I can think of one case where a LateFixedUpdate makes sense but I believe it is due to a Unity bug (I have not yet reported it since I am still in research mode). It appears that using Rigidbody.$$anonymous$$ovePosition causes wacky Rigidbody.velocity values. Have a look at the image below. Each log prints the following: "realtimeSinceStartup, position, velocity". Logs occur just before $$anonymous$$ovePosition is called, just after $$anonymous$$ovePosition is called and then in OnColliderStay. Very odd velocity values in there for sure. A LateFixedUpdate would allow calculating a proper velocity based on the previous and current positions.

alt text

avatar image whydoidoit · Mar 03, 2014 at 04:59 AM 2
Share

Wow that's really interesting!

avatar image prime31 · Mar 03, 2014 at 06:04 AM 1
Share

Bug report officially sent to Unity. Hopefully we get a fix soon.

avatar image apatton · Sep 26, 2016 at 09:23 PM 1
Share

Fattie's answer below was the trivial solution I needed, see https://docs.unity3d.com/$$anonymous$$anual/class-ScriptExecution.html

Show more comments
avatar image
5

Answer by Peter G · Apr 21, 2011 at 11:51 PM

Here's an idea:

I do this with all my code. This is a little confusing if you don't program, but it is actually faster than having lots of Update() calls.

  1. I create an event manager, then have all then have all my class have a psuedo-update function that they add to the event. Then I fire the event and they all get fired.

  2. Unity is single treaded. So if you call a function Unity will finish it before it continues onto its next task. So if you have two events, the second one should be called after the first one is completely finished working similar to a LateFixedUpdate().

Here is a sample:

using System; using UnityEngine; using System.Collections;

public class TickManager : MonoBehaviour {

 public event Action tick;
 public event Action lateTick;

 // Use this for initialization
 void Start () {
      StartCoroutine(FixedTick());
 }

 IEnumerator FixedTick() {
      for(;;) {
          if(tick != null)
               tick();
          if(lateTick != null)
               lateTick();
          yield return new WaitForFixedUpdate();
      }
 }

}

This will create 2 events. Then you can have classes register to them.

using System; using UnityEngine; using System.Collections;

public class SomeClass : MonoBehaviour {

 // Use this for initialization
 void Start () {

     TickManager eventManager = (TickManager)FindObjectOfType(typeof(TickManager));
     tickManager.tick += new Action (Tick);
     tickManager.lateTick += new Action(LateTick);

 }

 void Tick () {
         //This will get called as frequently as FixedUpdate
 }

 void LateTick () {
         //This should be called after the first one.
 }

}

By the way, if someone more knowledgeable than myself can tell me that my understanding of Unity's threading is completely wrong then please do ;).

EDIT: I managed to get it working with javascript. The first code needs to be in C# because I don't believe you can do events in javascript. But the second code can be in js with the following syntax:

var tickManager : TickManager;

function Start () { //using function types. Similar to an implicit delegate. tickManager.tick += Tick; tickManager.lateTick += LateTick;

 //Also supports anonymous functions
 tickManager.tick += function() {
          Debug.Log("Tick");
     };

}

function Tick () { Debug.Log("Fired on a FixedUpdate interval"); }

function LateTick () { Debug.Log("Called after the prior method"); }

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Joshua · Apr 22, 2011 at 12:27 AM 0
Share

Your understanding of Unity's threading is completely wrong! ^.^ nah it looks good :)

avatar image zmar0519 · Apr 22, 2011 at 01:11 AM 0
Share

Peter G, thank you so much, but would it be possible to get that code in js? if not, thats ok, seeing as some things cannot be done in js, but it would be nice to get it.

avatar image Peter G · Apr 22, 2011 at 02:30 AM -1
Share

Oh, another trick you can do. Create an interface that has these methods. Then have algorithm in your 1st script that finds instances of all classes that implement that interface. foreach($$anonymous$$onoBehaviour mB in the scene) { if( mB is IEvent$$anonymous$$anager) { //add to list } }

avatar image prime31 · Mar 03, 2014 at 04:07 AM 0
Share

This answer is indeed incorrect and @Peter G's understand of Unity threading is off a bit. See my answer for the details.

avatar image
4

Answer by Fattie · Dec 20, 2015 at 05:30 PM

Just for any beginners reading, if you stumble on to the type of problem outlined in the question here,

the trivial solution is almost always nothing more than using the script execution ordering system.

It's exactly why Unity added it, and it resolves 99.99% of such issues.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
4

Answer by AlkisFortuneFish · Oct 27, 2016 at 06:16 PM

So, the other answers are correctly mentioning all the reasons for which you should not have to do this, and this is fine. However, if you find yourself in a situation where there is a definite need for code to execute after FixedUpdate, the physics timestep and collision/trigger callbacks but before the next FixedUpdate frame, there is a way to do it.

In my case, we needed behaviour that prioritised particular triggers in a complex hitbox system, which required code to execute after all the trigger events. The code could have been pushed to the start of the next fixed update frame but that would potentially result to it executing an actual rendered frame late.

This is indeed possible and is exactly what WaitForFixedUpdate does. The current order of execution of callbacks and the physics step, as of Unity 5.4 and since at least Unity 5.2, is the following:

  1. FixedUpdate callbacks are executed

  2. Physics systems are stepped.

  3. Collision callbacks are executed

  4. WaitForFixedUpdate coroutine yields return.

  5. Steps 1-4 are repeated if if several physics steps can fit in the current update step.

  6. Update callbacks are executed.

Here's an example on the profiler timeline, with the steps annotated with the fixed frame count: Screenshot

Also note that this completely contradicts the current Unity documentation. I have consulted with Melv from Unity, who is responsible for the Physics2D system, and this is the intended behaviour. The documentation team has been notified to update the documentation.

The documentation has now been updated to reflect this information. The diagram was modified to show WaitForFixedUpdate returning after the physics update and all collision callbacks. Note that the text has not been modified and still states that it is run after all FixedUpdate calls are done. This should really now be the accepted answer for this, seeing that it actually answers the question.


waitforfixedupdate.png (13.2 kB)
Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image apatton · Oct 27, 2016 at 06:33 PM 0
Share

According to Unity, a yield WaitForFixedUpdate would occur before the physics step, see https://docs.unity3d.com/$$anonymous$$anual/ExecutionOrder.html

avatar image apatton apatton · Oct 27, 2016 at 06:56 PM 0
Share

I can't seem to access your screenshot, it gives me a 403

avatar image Narotak · Oct 25, 2017 at 10:43 AM 0
Share

This seems to work quite well for me so far. I needed to perform some corrections after the physics step (some custom physics). Simply:

 void Start() {
     StartCoroutine(LateFixedUpdate());
 }
 
 IEnumerator LateFixedUpdate() {
     while (true) {
         yield return new WaitForFixedUpdate();
         // Do late fixed update physics adjustments etc.
     }
 }

avatar image AlkisFortuneFish Narotak · Oct 25, 2017 at 10:55 AM 1
Share

Note that you can cache your WaitForFixedUpdate yield instruction, to save on allocations. :-)

avatar image
0

Answer by Bunny83 · Dec 20, 2015 at 06:04 PM

The best way to implement a late fixedupdate would be to implement a parallel implementation of FixedUpdate either in Update or LateUpdate. Since Update runs after the physics update it would be enough there. However we need some clever tricks to accomplish that.

Basically it would work like this:

 // LateFixedUpdateGenerator.cs
 using UnityEngine;
 
 public class LateFixedUpdateGenerator : MonoBehaviour
 {
     int currentFrame = -1;
     float lateFixedTime = 0;
 
     void Start()
     {
         lateFixedTime = Time.fixedTime;
     }
 
     void FixedUpdate ()
     {
         // catchup if FixedUpdate is called several times a frame
         if (currentFrame == Time.frameCount)
         {
             InvokeLateUpdate();
         }
         currentFrame = Time.frameCount;
     }
     
     void Update ()
     {
         if (Time.fixedTime > lateFixedTime || Time.fixedTime == 0f)
             InvokeLateUpdate();
         lateFixedTime = Time.fixedTime;
     }
     void InvokeLateUpdate()
     {
         lateFixedTime += Time.fixedDeltaTime;
         SendMessage("LateFixedUpdate", SendMessageOptions.DontRequireReceiver);
     }
 }

Just attach that script to a gameobject and other scripts on that game object will receive a LateFixedUpdate. So you can simply implement one like this in other scripts on the same gameobject:

 void LateFixedUpdate()
 {
     // ...
 }

The idea is that "Time.fixedTime" represents the current time from the physics systems point of view. If that value is increased a new Physics frame happend. Since we simply keep track of that value, if it hasn't changed between two frames (Update calls) no FixedUpdate has been called in between.

On the other hand if we enter FixedUpdate for the first time it should happen in a "new frame". So inside FixedUpdate we can use the frame counter to detect a new frame. However if FixedUpdate is called a second (or third, ...) time within the same frame we can detect that and just before the next FixedUpdate is called we quickly call our LastFixedUpdate for the last FixedUpdate call. The only problem is that in the case where FixedUpdate is called multiple times in a frame, the Time.fixedTime value inside LateFixedUpdate doesn't match the value it was in the corresponding FixedUpdate. Only the last call will match.

For example:

 //  method         fixedTime
 //  -----------------------------------
 //  FixedUpdate       5.0
 //  LateFixedUpdate   5.0
 //  Update            5.0
 //
 //  FixedUpdate       5.2
 //  LateFixedUpdate   5.4   <-- wrong
 //  FixedUpdate       5.4
 //  LateFixedUpdate   5.4  <-- correct
 //  Update            5.0
 //

Besides that little problem, everything else shoud work as expected. So the position should be updated in LateFixedUpdate.

Of course you need to set the execution order of the "LateFixedUpdateGenerator" before the normal time:

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bunny83 · Dec 20, 2015 at 07:00 PM 0
Share

Note: The only drawback with this approach is, that you can't control the execution order of the LateFixedUpdate methods. However they behave correctly, even with several scripts. Imagine two objects (AAA and BBB)

 AAA::FixedUpdate();
 BBB::FixedUpdate();
 AAA::LateFixedUpdate();
 BBB::LateFixedUpdate();
 AAA::Update();
 BBB::Update();

That assumes that the order AAA then BBB is the "natural" order. If you change the script execution order, the order of LateFixedUpdate won't change, as it's mainly driven by our seperate script. So if you place BBB before AAA it would look like this:

 BBB::FixedUpdate();
 AAA::FixedUpdate();
 AAA::LateFixedUpdate();
 BBB::LateFixedUpdate();
 BBB::Update();
 AAA::Update();

So it's still ensured that all LateFixedUpdate run together "sometime" after all FixedUpdate calls but before any Update()

If you need to mimic the exact behaviour, you would need to implement some kind of "subscriber" pattern where each script calls a "RequestLateFixedUpdate" method inside FixedUpdate which would allow you to store those in the same order as FixedUpdate was called. That would need a singleton approach ins$$anonymous$$d of a seperate script on each object.

If i find the time i post this solution as well ^^.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Coroutines vs Update/FixedUpdate/LateUpdate 2 Answers

What's the execution order of Updates of different objects? 1 Answer

Climb animation in Update or FixedUpdate or LateUpdate?, 1 Answer

Not sure if this should go in Update or FixedUpdate function 2 Answers

The name 'Joystick' does not denote a valid type ('not found') 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges