You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何用WireCube检测房间内Enemy以触发开门逻辑

2D Roguelike房间清敌开门逻辑实现

原脚本存在的问题

  • Start()中GameObject.FindGameObjectWithTag("Enemy")仅能获取单个敌人,无法覆盖房间内所有敌人,且无法动态响应敌人销毁的情况
  • 缺少动态检测房间范围内敌人数量的逻辑,无法触发开门条件

补全后的完整脚本

using UnityEngine;

public class RoomClean : MonoBehaviour
{
    // 引用需要开启的房门对象,在Inspector中赋值
    public GameObject door;
    // 房间的范围尺寸,与Gizmos绘制的WireCube保持一致,可在Inspector中调整
    public Vector3 roomSize = new Vector3(50, 50, 50);
    // 标记房门是否已开启,避免重复执行开门逻辑
    private bool isDoorOpened = false;

    void Update()
    {
        // 房门已开启则跳过检测
        if (isDoorOpened) return;

        // 检测当前房间范围内所有Enemy层的对象(2D场景用Physics2D)
        Collider2D[] enemiesInRoom = Physics2D.OverlapBoxAll(
            transform.position, 
            roomSize, 
            0f, 
            LayerMask.GetMask("Enemy")
        );

        // 范围内无敌人时触发开门
        if (enemiesInRoom.Length == 0)
        {
            // 此处替换为你的开门逻辑,比如激活房门、播放动画等
            door.SetActive(true);
            isDoorOpened = true;
        }
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        // 使用roomSize变量保证绘制范围与检测范围一致
        Gizmos.DrawWireCube(transform.position, roomSize);
    }
}

关键说明

  1. 碰撞检测配置

    • 确保敌人对象添加Collider2D组件(如BoxCollider2D),并将其所在Layer设置为"Enemy"
    • 若需用Tag而非Layer检测,可遍历enemiesInRoom数组判断每个对象的Tag:
      bool hasEnemy = false;
      foreach (var col in enemiesInRoom)
      {
          if (col.CompareTag("Enemy"))
          {
              hasEnemy = true;
              break;
          }
      }
      if (!hasEnemy) { /* 开门逻辑 */ }
      
  2. 开门逻辑适配

    • 房门初始状态建议设为SetActive(false),根据需求替换door.SetActive(true)为实际开门行为(如播放动画、修改位置等)
  3. 3D场景适配

    • 若为3D游戏,将Physics2D.OverlapBoxAll替换为Physics.OverlapBoxAll,Collider2D替换为Collider

内容的提问来源于stack exchange,提问作者Charles Marchand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:34:59