如何在Unity中删除带有标签的gameObject?

问题描述

我有一个由6个块组成的地图,带有标签LevelBlock。汽车离开该街区后,当前正在我要删除的街区。现在,我的代码删除随机的LevelBlock,但没有删除汽车之前所在的那个。如何删除不再使用的LevelBlock?

Screenshot of the map here

这是我的代码

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);
}

}

解决方法

在您的脚本中

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

只是使用标记为LevelBlock的第一个对象并将其删除。

我正在收集您提供的脚本在代码块上。如果真是这样,那么进行修复很简单。也许像

IEnumerator WaitAndDestroy()
{
   
    yield return new WaitForSeconds(delay);

    // Destroy the LevelBlock
    Destroy(gameObject);
}

再次假设该脚本位于您的代码块中,但是Destroy(gameObject)(带有小写的g)告诉它要销毁自己。

编辑:很糟糕,您需要获取父对象并销毁该对象,我有一段时间没有碰到团结了

var parent = gameObject.transform.parent.gameObject;

执行此操作的方法有很多,这取决于对象的设置方式,但这将使您成为父对象,然后可以销毁它。

,

FindWithTag返回带有遇到标签的第一个遇到的GameObject。

您实际要销毁的对象是附加了ExitTrigger的{​​{1}}的父对象。

您可以像这样传递它

LevelBlockScript