There are parts of both Seyed's answer and Daniel's answer that are correct.
However, I would advocate for different code.
For example, Daniel does this:
public bool run = false;
void Update () {
if(Input.GetKey(KeyCode.R)) {
run = true;
GetComponent<Animation>().Play("Jump");
GetComponent<Animation>().wrapMode = WrapMode.Loop;
}
}
Which doesn't fix the issue that run
will be true forever (the identified problem). All it does is make the effects of that no longer dependent on it.
Instead, I would suggest this:
void Update () {
bool run = false;
if(Input.GetKey(KeyCode.R)) {
run = true;
}
if(run) {
GetComponent<Animation>().Play("Jump");
GetComponent<Animation>().wrapMode = WrapMode.Loop;
}
}
Which makes the scope of run
function scope rather than class scope (which lets it reset) or use an else
statement that resets it, or remove it entirely (as doing it purely based on the input is fine, just that the field is no longer relevant). What you do depends on whether or not you're accessing that field from outside the class or in another method.
Then, both Daniel and Seyed are still using Input.GetKey(KeyCode.R)
, which means that the key is not rebindable and if you ever decide that "You know what, I don't want Run to be R, I want it to be Left Shift" you have to change it inside your code anywhere and everywhere you're using KeyCode.R
.
Instead use Input.GetButton("Run")
and use the input settings (Edit -> Project Settings -> Input) menu to configure your keyboard input. Alternatively you can get an asset like Rewired that allows you to do key rebinding in game rather than Unity's setup which prompts the user before the game and looks wholly unprofessional (and it only works for Windows and Mac builds, webgl and console builds won't show it and your keybinds are again permanent).