Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

unity3d - Is it really wrong to use Input.GetKey() on FixedUpdate?

We know there's a "rule" that Input functions shouldn't be used inside the FixedUpdate(); Input.GetKeyDown() may not work if we do so, but is it really wrong to use Input.GetKey()?

Let's say we want to fire something when pressing and holding a key at some rate that is not dependent on hardware performance. I don't want to create a logic to control this using delta time or writing key detection code in Update and firing code in FixedUpdate.

Doesn't make sense to just do everything inside FixedUpdate? What can happen - we may lose some key pressed events, the ones that we didn't want anyway, to keep our desired rate.

But what if one single key event happens, can we lose it? Is there a reset after Update, so we won't see it on FixedUpdate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the GetKeyDown docs:

You need to call this function from the Update function, since the state gets reset each frame

So yes, the Input state is reset each frame meaning hardware will have an effect depending on how frequently Update fires between FixedUpdate.

There really isn't an easy way to avoid creating a copy of the Input that is used by FixedUpdate, though I would suggest reevaluating your logic to move things in to Update.

Update:

Regarding Rutter's comment below. I just noticed the OP was asking about GetKey(), what I wrote about GetKeyDown() remains true for GetKey() though the documentation doesn't explicitly say so.

This can be verified by going in to the Time Manager and changing the FixedUpdate rate to some long interval like 1 second. Then do something like:

void FixedUpdate() {
    if(Input.GetKey(KeyCode.D)){
        Debug.Log("D-Key Down");
    } else {
        Debug.Log("No key down");
    }
}

If you press and release 'D' between the 1 second fixed frames you will only see "No Key Down".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...