Search Unity

Question Unable to make Input.GetKey work

Discussion in 'Input System' started by bwool, May 26, 2023.

  1. bwool

    bwool

    Joined:
    Mar 30, 2023
    Posts:
    22
    Apologies if this is a dumb question.

    I'm trying to create a custom physics system for a unique racing game, and I've begun to get the following error message from my player controller script:

    Screenshot 2023-05-25 at 7.47.07 PM.png

    Here is the code I'm using:



    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.EventSystems;

    public class playerController : MonoBehaviour
    {
    public GameObject player;

    bool leftInput = Input.GetKey(KeyCode.A);
    bool rightInput = Input.GetKey(KeyCode.D);
    bool forwardInput = Input.GetKey(KeyCode.W);
    bool backInput = Input.GetKey(KeyCode.S);

    float smooth = 5.0f;
    float tiltLeft = -60.0f;
    float tiltRight = 60.0f;

    private void Update()
    {
    if (leftInput == true)
    {
    float tiltAroundZ = Input.GetAxis("Horizontal") * tiltLeft * Time.deltaTime;
    };

    if (rightInput == true)
    {
    float tiltAroundZ = Input.GetAxis("Horizontal") * tiltRight * Time.deltaTime;
    };

    if (forwardInput == true)
    {
    transform.position = player.transform.position + new Vector3(0, 0, 20 * Time.deltaTime);
    };

    if (backInput == true)
    {
    transform.position = player.transform.position + new Vector3(0, 0, -10 * Time.deltaTime);
    };
    }


    }
     

    Attached Files:

  2. if this was one of the first attempts at coding in unity, it's not bad! But, a couple of things:

    First, use code tags in the forum when you submit code, more info about that here.

    Regarding your problem:
    this way you would only read the keyboard one time when this class is instantiated anyway.
    And you need constant read out, so you can react to player input during the application running, right?

    So, initialize the
    leftInput
    -like variables with
    false
    (or simple don't initialize them, same thing) and then move the read into the beginning of the Update method.

    Code (CSharp):
    1. private void Update ()
    2. {
    3.     leftInput = Input.GetKey(KeyCode.A);
    4.     rightInput = Input.GetKey(KeyCode.D);
    5.     forwardInput = Input.GetKey(KeyCode.W);
    6.     backInput = Input.GetKey(KeyCode.S);
    7. [...]
    Later you can learn more effective ways to handle input, but it is great for a first.
     
    Ryiah likes this.
  3. bwool

    bwool

    Joined:
    Mar 30, 2023
    Posts:
    22

    That worked! Thanks so much for your response, and noted regarding the code tags.