Cri
Cri

Reputation: 95

Input.GetkeyDown returning true without button press

Im making a system where you can press a certain key and it will place down an object at your mouse location. Every time you press the key '1' it should place it down at the mouse location but for some reason every frame the Input.GetKeyDown("Alpha1"); is registered as true so wherever i move my mouse it places the block down no matter what I press. This has been happening to me alot recently and I cant seem to find any answers.

using UnityEngine;

public class CubePlacer : MonoBehaviour
{
    private Grid grid;
    public KeyCode place;

    private void Awake()
    {
        grid = FindObjectOfType<Grid>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(place)) ;
        {
            RaycastHit hitInfo;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hitInfo))
            {
                PlaceCubeNear(hitInfo.point);
            }
        }
    }

    private void PlaceCubeNear(Vector3 clickPoint)
    {
        var finalPosition = grid.GetNearestPointOnGrid(clickPoint);
        GameObject.CreatePrimitive(PrimitiveType.Cube).transform.position = finalPosition;

        //GameObject.CreatePrimitive(PrimitiveType.Sphere).transform.position = nearPoint;
    }
}

Upvotes: 1

Views: 106

Answers (1)

NibblyPig
NibblyPig

Reputation: 52952

if (Input.GetKeyDown(place)) ; // <--- remove this semi colon
        {
            RaycastHit hitInfo;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hitInfo))
            {
                PlaceCubeNear(hitInfo.point);
            }
        }

You need to remove the semicolon after the If statement. It terminates the line and causes the block afterwards to execute every time the Update() method is called.

Upvotes: 6

Related Questions