I’m currently trying to make a sort of barrier that prevents the player from passing it without killing the enemies in a area, my original plan was for a game object with a huge box collider2d to detect if there was anything with the Tag enemy, and if there wasn’t, it would destroy itself. I tried to use some debugs to check if the action happened, but nothing
Here is the script i made with a friend’s help:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DetectEnemy : MonoBehaviour
{
public GameObject parede_Invisivel; // Reference to the Parede_Invisivel GameObject
private void OnTriggerEnter2D(Collider2D other)
{
// Check if the entering collider is tagged as an enemy
if (other.CompareTag("Enemy"))
{
Debug.Log("ainda a inimigos");
// There's an enemy in the box collider, do nothing
return;
}
// There's no enemy in the box collider, destroy the Parede_Invisivel GameObject
Destroy(parede_Invisivel);
Debug.Log("inimigo destroido2");
}
private void OnTriggerExit2D(Collider2D other)
{
// Check if the exiting collider is tagged as an enemy
if (other.CompareTag("Enemy"))
{
// An enemy has exited the box collider, do nothing
return;
}
// Check if there are still enemies in the box collider
Collider2D[] colliders = Physics2D.OverlapBoxAll(transform.position, transform.localScale / 2, 0f);
foreach (Collider2D collider in colliders)
{
if (collider.CompareTag("Enemy"))
{
Debug.Log("ainda a inimigos 2");
// There's still an enemy in the box collider, do nothing
return;
}
}
// There are no enemies left in the box collider, destroy the Parede_Invisivel GameObject
Destroy(parede_Invisivel);
Debug.Log("inimigo destroido1");
}
// Visualize the box collider in the Scene view
private void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireCube(transform.position, transform.localScale);
}
}