darren bask
darren bask

Reputation: 11

What is the right way to use get key down in this scenario?

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

public class Q : MonoBehaviour
{

    void OnTriggerStay2D(Collider2D collision)
    {        
        if (Input.GetKeyDown("q"))
        {
            Destroy(collision.gameObject);

        }
    }
}

ok so i wrote code that is supposed to detect when another object is colliding with it to allow the player to press a key to destroy the collider. the code is able to detect a collider but is not able to detect a key press while the collider is being detected. I have zero clue to as why this is happening so if anybody can help that would be great thank you

Upvotes: 1

Views: 50

Answers (1)

Patrick Martin
Patrick Martin

Reputation: 3131

If you look at the documentation for GetKeyDown, you'll see that it needs to be in your Update callback. This would be super easy to fix though!

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

public class Q : MonoBehaviour
{
    bool _qPressed;

    void Update()
    {
        _qPressed = Input.GetkeyDown("q");
    }


    void OnTriggerStay2D(Collider2D collision)
    {        
        if (_qPressed)
        {
            Destroy(collision.gameObject);

        }
    }
}

Upvotes: 1

Related Questions