Unity2D玩家标签碰撞检测到敌人标签后敌人于2s后销毁的代码
时间: 2024-03-23 13:39:38 浏览: 18
可以使用Unity的协程(Coroutine)来实现这个功能,代码如下:
```csharp
using UnityEngine;
System.Collections;
public classController : MonoBehaviour
{
float destroyDelay = 2f; // 销毁延迟时间
public string enemyTag = "Enemy"; // 敌人标签名称
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag(enemyTag))
{
StartCoroutine(DestroyEnemy(other.gameObject));
}
}
IEnumerator DestroyEnemy(GameObject enemy)
{
yield return new WaitForSeconds(destroyDelay);
Destroy(enemy);
}
}
```
这段代码中,我们在玩家的脚本中实现了 OnTriggerEnter2D 方法,当玩家碰到带有敌人标签的物体时,我们会调用协程 DestroyEnemy 来销毁敌人。DestroyEnemy 方法中使用了 yield return new WaitForSeconds(destroyDelay) 来等待指定的时间,最后再销毁敌人。