c# - 如果它击中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);
}
}
}
解决方案
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);
}
}
干杯!
推荐阅读
- apache - Mod Rewrite 停止规则?
- git - Bit local repo:从旧提交中删除文件
- npm - 在 PhpStorm 中配置 node-sass
- javascript - 什么是 TypeError: require(...)(...) is not a function 当我尝试运行我的 playWright 脚本时?
- xml - 如何检索 XML 参数实体的值?
- kubernetes - 用于 2 组注释的 Helm 模板
- reactjs - 渲染异步获取的数据
- javascript - 使用多个键在 Angular2 中过滤地图
- java - 如何使用迭代器为两个类实现接口
- javascript - 如何根据函数中的给定参数为对象分配 n 个属性?