- Home /
How can i make it so that when a gameobject enters a collider, it gets destroyed. All of this while being able to toggle said collider by pressing a key
So i have been trying for the past few days how to do as I say in the title but i havent made much progress, if at all
What i have done is, I created an empty object and added a box collider to it, then i wrote this code on the player's script to make the empty toggleable, which hasnt worked as it only sets it to false when the empty is set to true.
if (Input.GetKeyDown(KeyCode.E) && toggleAttack)
{
attack.SetActive(true);
toggleAttack = false;
}
if (Input.GetKeyDown(KeyCode.E) && toggleAttack == false)
{
attack.SetActive(false);
toggleAttack = true;
}
Then on the empty's script i wrote this so that it would destroy a certain type of gameobjects and also follow the player
{
public GameObject player;
public GameObject attack;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = player.transform.position + new Vector3(-0.8f, 0, -1);
}
private void OnTriggerEnter(Collider other)
{
if (CompareTag("Enemy"))
{
Destroy(other.gameObject);
GetComponent<SpawnManager>().currentEnemies -= 1;
}
}
}
Which also doesnt work as the empty just ignores any of the gameobjects that enter its trigger
Any help would be appreciated
Answer by starviw · Jul 14, 2021 at 08:02 AM
hey, first thing first, you can write the player's code as below just to simplify it
if (Input.GetKeyDown(KeyCode.E))
{
attack.SetActive(toggleAttack);
toggleAttack = !toggleAttack;
}
secondly, you should compare other.gameobject.tag to compare the tag of the object you collided with and not just CompareTag, which i'm not sure what it does since it's a function by itself.
thirdly, you need to check that at least one of the objects, be it empty or the enemy, has rigidbody on it for collisions to occur.
Hey there, tried all 3 of the things you said and worked out perfectly as i wanted it to, thank you very much and have a great day.
Your answer
