- Home /
GetKeyDown not working,I can't destroy self object when I press a button using the Input.GetKeyCode , I'm new to unity so please help!
Need help! I can't destroy objects on Input.GetKeyDown(Keycode.E) It's on line 31 and I can't seem to do anything about it, when I put it in the Update void, it still doesn't work, but the print command runs well and the console prints the "Item" string perfectly when I'm near the object Any idea how I could get this to work?
using UnityEngine;
public class Interactable : MonoBehaviour
{
public float radius = 1.85f;
private int isNearObject = 0;
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, radius);
}
public void Update()
{
if ((Vector3.Distance(GameObject.FindGameObjectWithTag("Player").transform.position, this.gameObject.transform.position) <= radius) && (isNearObject == 0))
{
isInteracting();
}
else if ((Vector3.Distance(GameObject.FindGameObjectWithTag("Player").transform.position, this.gameObject.transform.position) > radius) && (isNearObject == 1))
{
isNotInteracting();
}
}
public void isInteracting()
{
if (this.gameObject.CompareTag("Items"))
{
print("Item");
if(Input.GetKeyDown(KeyCode.E))
{
Destroy(this.gameObject);
}
isNearObject = 1;
}
if (this.gameObject.CompareTag("Doors"))
{
print("Door");
isNearObject = 1;
}
}
public void isNotInteracting()
{
print("Away");
isNearObject = 0;
}
}
did you check if your tags are correct and is does "Item" get printed in debug log? Also GetKeyDown only checks one frame.
Answer by DenisIsDenis · Jun 22, 2021 at 01:34 PM
In your code, the player must press the E key in the same frame when he enters the Item's radius (which is almost impossible). You need to move the code below into the Update()
function:
if(Input.GetKeyDown(KeyCode.E) && CompareTag("Items") && isNearObject == 1)
{
Destroy(this.gameObject);
}
(Note: this code CompareTag("Items")
is identical to this one this.gameObject.CompareTag("Items")
).