Search code examples
c#unity-game-enginegame-developmentdestroy

How to delete one gameObject with a tag in Unity?


I have a map made of 6 blocks with a tag LevelBlock. After the car leaves the block it was currently on I want to delete that block. Now my code deletes random LevelBlock but not the one the car was previously on. How do I delete the LevelBlock that is no longer in use?

Screenshot of the map here

Here's my code:

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

public class TriggerExit : MonoBehaviour {

public float delay = 5f;

public delegate void ExitAction();
public static event ExitAction OnChunkExited;

private bool exited = false;

private void OnTriggerExit(Collider other)
{
    CarTag carTag = other.GetComponent<CarTag>();
    if (carTag != null)
    {
        if (!exited)
        {
           exited = true;
           OnChunkExited();
           StartCoroutine(WaitAndDestroy());
        }
    }
}
    
IEnumerator WaitAndDestroy()
{
   
    yield return new WaitForSeconds(delay);

    // Destroy the LevelBlock
    var block = GameObject.FindWithTag("LevelBlock");
    Destroy(block);
}

}


Solution

  • FindWithTag returns the very first encountered GameObject with according tag.

    The object you actually want to destroy is the parent of your ExitTrigger which has the LevelBlockScript attached.

    You could pass it on like e.g.

    private void OnTriggerExit(Collider other)
    {
        CarTag carTag = other.GetComponent<CarTag>();
        if (carTag != null)
        {
            if (!exited)
            {
               exited = true;
               OnChunkExited();
               StartCoroutine(WaitAndDestroy(GetComponentInParent<LevelBlockScript>().gameObject));
    
               // or also simply
               //StartCoroutine(WaitAndDestroy(transform.parent.gameObject))
            }
        }
    }
        
    IEnumerator WaitAndDestroy(GameObject block)
    {
       
        yield return new WaitForSeconds(delay);
    
        // Destroy the LevelBlock
        Destroy(block);
    }