Collider to Delete Object

Hi,

I’m trying to delete an object when it collides with a box only when a key is down. In this case the “j” key. I tried working with OnTiggerStay/OnTriggerEnter, which worked, but the response time was very bad. It would only seem to work when the object came in contact with the boxes edge. So in this example I have an object “HighHat”, when it collides with any other object and the j key is down I want it to disappear. If anyone could help me out that would be great. I’m not to savvy with Unity or C#. So if you were to ask “why did you do ____?” I unfortunately don’t really have a good response. I did it because it worked the best at the time.

Thanks,

using UnityEngine;
using System.Collections;

public class DestroyHH : MonoBehaviour 
{
	public int scoreValue;
	private GameController gameController;
	
	
	void Start ()
	{
		GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
		if (gameControllerObject != null)
		{
			gameController = gameControllerObject.GetComponent <GameController>();
		}
		if (gameController == null)
		{
			Debug.Log ("Cannot find 'GameController' script");
		}
	}

	void OnCollisionEnter(Collider other)
	{
	if (other.tag == "HighHat") 
	{
			if(Input.GetKeyDown (KeyCode.J))
			{
				Destroy (other.gameObject);
				gameController.AddScore (scoreValue);
			}
		}
	}
}

“Input.GetKeyDown” means that the button must be pressed at the precise moment that the object enters collision.

I suspect you may actually wish to use “Input.GetKey”, which will check if when the collision occurs, the key is already pressed.

If you don’t want the player to be able to simply hold down the key indefinitely and have the objects be destroyed any time a collision occurs, you can use a bool and a timer. When the player presses down J, set the bool and start counting down. If the objects collide while the bool is set, destroy the object. Once the timer reaches a certain point, set the bool to false. The player must then release the key, the timer will reset, then it can be pressed again. You can use this to give the player a very brief grace period (say 0.5 seconds) to hit the key before the collisions for them to destroy the object in question.

Hope this helps!