(Input.GetKeyDown("space")) or (Input.GetKeyDown(KeyCode.Space))?
The scriptingAPI page it lists both. Is one better than the other? I just found out after writing if(other.tag == "Player") for months that if(other.CompareTag == ("Player")) is more efficient... so is one of the keyDown versions better than the other?
Answer by Hellium · Apr 20, 2018 at 08:27 PM
Input.GetKeyDown( string )
requires a string defined in the InputManager
. So, if your InputManager is "empty", this function won't work. Without mentionning that space
can be mapped with an other key than the spacebar (in the input manager or by the user if you have enabled the configuration box)
Input.GetKeyDown( KeyCode )
requires a specific key, no matter what.
Using the KeyCode
version is clearly more efficient than the string version, but is less flexible.
Great thanks. $$anonymous$$akes perfect sense. I 'm still in shock how the CompareTag being more efficient than .tag== "string". Is this fairly new ( post version 3.4)? Because I learned on if (other.tag == "Player") which I think I got from the S$$anonymous$$lth tutorial. I didn't know ANYTHING about coding back then so doubt I would have come up with it on my own.
According to the doc, CompareTag
is available since Unity 4.0.
There are several optimization tricks in Unity you will learn little by little. For example the static function Animator.StringToHash
creates a hash of the specified string parameter so that you can call Animator.SetTrigger
(or any other SetXXX
) with this hash ins$$anonymous$$d of the string, which is also more efficient.
Thanks, that is another script tip I appreciate. All may animations are ani.SetTrigger just like all my trigger enters are (other.tag=="Player"). Not that I experience any lags in a build but even if it buys me 1 FPS it's worth gradually upgrading as I revisit scripts
Your answer
![](https://koobas.hobune.stream/wayback/20220612161211im_/https://answers.unity.com/themes/thub/images/avi.jpg)