首页 > 解决方案 > 如果它击中NOTHING,统一删除对象

问题描述

我正在创建一个 roguelike 游戏,我需要在它生成后立即删除一堵墙,但前提是它不与标记为Wall+Ground的对象发生碰撞。我尝试了 OnTriggerEnter2D 或 OnColliderEnter2D 函数,但只有在墙壁与任何物体发生碰撞之前,它才会继续接触任何东西。这是我尝试调整的代码,但我不知道可以使用的功能:

public class BlockWall_Destroyer : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag != "Wall+Ground" | other.gameObject.tag != "Player")
        {
            Destroy(gameObject);
        }
    }
}

标签: c#unity3dcollision-detectioncollision

解决方案


OnTriggerEnter2D 只在发生碰撞时调用,如果没有碰撞则不会运行。

正如此答案中所建议的那样,您必须在 MonoBehavior 开始时等待一帧才能知道它是否发生了碰撞。

以下是它如何适用于您的案例:

public class BlockWall_Destroyer : MonoBehaviour
{
    private bool collided = false;

    void Start() {
         StartCoroutine(CheckForCollision());
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Wall+Ground") // (/!\ condition has been inverted here)
        {
            collided = true;
        }
    }

    IEnumerator CheckForCollision() {
        yield return null; // wait a frame for OnTriggerEnter2D to be (maybe) called
        if (!collided)     // check on the next frame if there was any collision
            Destroy(gameObject);
    }
}

干杯!


推荐阅读