- Home /
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!!! :)
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.
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.
@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.
Bug report officially sent to Unity. Hopefully we get a fix soon.
Fattie's answer below was the trivial solution I needed, see https://docs.unity3d.com/$$anonymous$$anual/class-ScriptExecution.html
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.
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.
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"); }
Your understanding of Unity's threading is completely wrong! ^.^ nah it looks good :)
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.
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 } }
This answer is indeed incorrect and @Peter G's understand of Unity threading is off a bit. See my answer for the details.
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.
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:
FixedUpdate callbacks are executed
Physics systems are stepped.
Collision callbacks are executed
WaitForFixedUpdate coroutine yields return.
Steps 1-4 are repeated if if several physics steps can fit in the current update step.
Update callbacks are executed.
Here's an example on the profiler timeline, with the steps annotated with the fixed frame count:
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.
According to Unity, a yield WaitForFixedUpdate would occur before the physics step, see https://docs.unity3d.com/$$anonymous$$anual/ExecutionOrder.html
I can't seem to access your screenshot, it gives me a 403
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.
}
}
Note that you can cache your WaitForFixedUpdate yield instruction, to save on allocations. :-)
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:
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
Follow this Question
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