Home > other >  Unity C# GetKey() not working when i set a variable with the button i want pressed in
Unity C# GetKey() not working when i set a variable with the button i want pressed in

Time:06-18

Im trying to make it so that you can assign whatever key you want to make the player jump/move via unity itself and not the script. I want to set public variables with the keycodes of each key and use these keys to start the functions. It doesnt work for the arrow keys and i cant find much info on the GetKey() keycodes. I am aware of the thing you can do on the project settings that sets a key for each action and then call the action but i dont want to do that.

Here is my code: // the script name is "Movement" and on the object is attached a rigidbody2D with the gravity on 1.5 and a box collider2D

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

public class Movement : MonoBehaviour
{
    public int JumpHeight;
    public int MoveSpeed;
    private Rigidbody2D rb;
    public string JumpButton;
    public string MoveRightButton;
    public string MoveLeftButton;
    // Start is called before the first frame update
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    private void Update()
    {
        if(Input.GetKeyDown(JumpButton))
        {
            rb.velocity = new Vector3(0, JumpHeight, 0);
        }
        if(Input.GetKey(MoveRightButton))
        {
            rb.velocity = new Vector3(MoveSpeed, 0, 0);
        }
        if(Input.GetKey(MoveLeftButton))
        {
            rb.velocity = new Vector3(MoveSpeed*-1, 0, 0);
        }
    }
}

CodePudding user response:

You should try using the KeyCode type instead of the string type for Unity input to avoid issues like this. I would suggest briefly reading:

enter image description here

  • Related