If Else problem
Hello, i'm new to this unity. so i have this code, when i press enter once, it always return true first then quickly return false. is this common thing? or is there something wrong in my code?
public float maxSpeed;
float accel = 0;
int check;
// Use this for initialization
void Start () {
accel = maxSpeed / 5;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.Return) && check == 0) {
check = 1;
} else {
check = 0;
}
if (check == 1) {
transform.Rotate (Vector3.forward, maxSpeed * Time.deltaTime);
}
Debug.Log ("check = " + check);
}
Answer by Dave-Carlile · Oct 10, 2015 at 01:15 PM
According to the GetKeyDown documentation, the function returns true only on the frame when the key was pressed. It won't return true again until the key is released and then pressed again, so that is the correct behavior. This would be used when you only want something to happen once on a keypress and not repeat over and over each frame.
If you want to check the actual state each frame then you'd use Input.GetKey instead which always gives you the current up/down state of the key.
I'd suggest taking a look at this tutorial video: https://unity3d.com/learn/tutorials/modules/beginner/scripting/get-button-and-get-key
yeah you right. so what the best method to use for if else beside getkey and getbutton?? i already seen that video. but no. i want a single button that if press one then return true and then if press again then return false.
Okay, I wasn't understanding what you wanted... So you want the object to start out stationary, and when you press the button it starts rotating and will keep rotating until you press the button again?
You're close in that you're trying to toggle a value back and forth between 0 and 1. But you don't need an else at all..
bool rotate;
void Update()
{
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Return))
{
rotate = !rotate;
}
if (rotate)
{
transform.Rotate (Vector3.forward, maxSpeed * Time.deltaTime);
}
}
!
is the not
operator. It takes a boolean value and returns the opposite. So !true = false and !false = true. Booleans are a great way to toggle a value back and forth. So in my example, each time the Return key is pressed it will toggle the value of rotate
to the opposite of whatever it is now.
Then the rotate code is put inside an if
so it only executes when rotate
is true.
thank you. this is what i'm looking for. i didnt know if you can do like that.
Your answer
![](https://koobas.hobune.stream/wayback/20220612040732im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to put an if statement inside an if statement? 3 Answers
If/else statement is always else 1 Answer
How to use IF in Unity for selection MyScript 1 Answer
Simple toggle not working 1 Answer