if I detect a GetKeyDown in FixedUpdate, it will miss the input if the frame only runs Update.
Conversely, if I detect GetKeyDown in Update, could it be missed if the frame only runs FixedUpdate?
FixedUpdate() is a fraud. It doesn’t run independent of the frame rate. Instead it runs as many times as needed each frame in order to catch up to its target speed. That means it could run multiple times or it could run zero times. If you store the value of GetKeyDown() in Update() it will be available to FixedUpdate().
GetKeyDown() and GetKeyUp() don’t work in FixedUpdate() because the code that handles their current state isn’t being executed with each FixedUpdate() but with Update(). So if you try to use them in FixedUpdate() you will see incorrect state info.
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 befo…
Conversely, if I detect GetKeyDown in Update, could it be missed if the frame only runs FixedUpdate?
There is no such thing, as far as I know. Update runs
every
frame.
thank you for all the helps.
after some research and some testing using the following script.
i believe that
the GetKeyDown always pickup by
Update
with no miss.
the GetKeyDown always detect at the
Update
.
If GetKeyDown called in
FixedUpdate
it will use the key-state at the last Update.
If the
FixedUpdate
run 10 times faster than
Update
, if key pressed at the last
Update
frame, all 10
FixedUpdate
will consider the GetKeyDown is True. Even only press the key once.
using UnityEngine;
public class test_fixed_update_update_getKeyDown : MonoBehaviour
int total_key_down = 0;
int keyDown_FixedUpdate = 0;
int keyDown_Update = 0;
void Awake()
// Time.fixedDeltaTime = 0.04f; //25fps
// Application.targetFrameRate = -1;
// Application.targetFrameRate = 50;
// Application.targetFrameRate = 25;
Application.targetFrameRate = 5;
void FixedUpdate()
if (Input.GetKeyDown(KeyCode.H))
keyDown_FixedUpdate++;
print($"Fixed:{keyDown_FixedUpdate} Update:{keyDown_Update}");
void Update()
if (Input.GetKeyDown(KeyCode.H))
keyDown_Update++;
if (Input.GetKey("shoot") && Time.time>shootTime)
Instantiate(bullet,transform.position,transform.rotation);
shootTime=Time.time+1;
if (Input.GetKey("poop") && poopAvailable)
Instantiate(poop,transform.position,transform.rotation);
poopAvailable=false;