I write a simple code, but the keycode code always thinks that the button is pressed, even when I didn’t press it. Even when I unplug my keyboard, it’s still return true, or detecting that I press the key. Please answer
Here’s the code
using UnityEngine;
public class PlayerMovement :MonoBehaviour
{
public Rigidbody rb;
//Update once per frame
void Update()
{
if (Input.GetKey(Keycode.W));
{
rb.AddForce(0, 0, 500);
}
}
}
I see 3 errors in your code:
- MoniBehaviour doesn’t exist in unity, you want MonoBehaviour
- void update(), should be changed to void Update().
- Your if statement is missing the first parenthesis.
The above code should be changed to:
using UnityEngine;
public class PlayerMovement :MonoBehaviour
{
public Rigidbody rb;
//Update once per frame
void Update()
{
if( Input.GetKey(Keycode.W))
{
rb.AddForce(0, 0, 500);
}
}
}
You have a semicolon after your if statement. That means you created an empty if statement without a body. The code block that follows will run unconditionally. It should be
if (Input.GetKey(Keycode.W))
{
rb.AddForce(0, 0, 500);
}