- Home /
if statement not working
I was trying to implement a sprint mechanic and when doing an if statement, and both variables never stayed the same. Note: the default value of speed is walk speed, and the bool is false by default My Code: if(Input.GetKeyDown(KeyCode.LeftShift)) { speed = runSpeed; isRunning = true; } else { isRunning = false; speed = walkSpeed; }
Answer by 82MiddleMan · Jun 29, 2020 at 05:25 PM
You are using Input.GetKeyDown, which I believe only registers for the 1 frame it is pushed down on. Try using Input.GetKey. That should be true for every frame it's pushed down for.
okay, thank you, I just changed it and it worked. I just started learning c# and this is one of my first scripts I made without a tutorial.
Answer by logicandchaos · Jun 29, 2020 at 05:26 PM
EDIT: It's because you are using Input.GetKeyDown, you should use Input.GetKey
I'm not sure what you are asking, but there is nothing wrong with that if statement, there must be something wrong with how it is called or where in the code it is. You can test out what get run and not by using debug logs:
Debug.Log("About to check if statement");
if(Input.GetKeyDown(KeyCode.LeftShift))
{
Debug.Log("true");
speed = runSpeed;
isRunning = true;
}
else
{
Debug.Log("false");
isRunning = false;
speed = walkSpeed;
}
Debug.Log("speed: "+speed);
Debug.Log("isRunning: "+isRunning);
Adding those logs will give you insight to what is happening in your code. Posting the rest of your code will help people find the issue.
Your answer
Follow this Question
Related Questions
How to call unity event once every time my object reach destination in Update()? 1 Answer
Problem comparing contents of arrays 1 Answer
How do i make two if statements 3 Answers
Why is this simple C# script not working? 3 Answers
Trigger to play music needs to check if the same music is already playing 1 Answer