c# - 无法在 RaycastHit2D 上执行 If 语句,除了最上面的语句
问题描述
在我的 Unity 2D 游戏中,我在同一个 GameObject 上设置了 3 个不同的 2D Raycast,用于在boolean和if语句的帮助下进行分数检测。今天讨论的对象是一个从右到左滚动的圆环,玩家(气球)必须通过或避免使用上下运动。玩家通过环面时获得更多积分,而不是绕过环面。
问题:当在圆环内检测到玩家时,Rayhit1 正确返回。但是 Rayhit2 和 Rayhit3 的代码不会执行。有趣的是,如果我将 Rayhit2 的代码放在 Rayhit1 之前,它就会执行。Rayhit3 也是如此。
这是“hit1”部分,例如:
if(!Rayhit1)
{
if(hit1.collider.name == "GameObject")
{
RayHit1 = true;
score.value += 30;
}
}
if(!hit1)
{
RayHit1 = false;
}
以下是我的代码片段,涉及检测分数的过程:
private bool RayHit1 = false;
private bool RayHit2 = false;
private bool RayHit3 = false;
void Update()
{
int layer = 9;
int layerMask = 1;
RaycastHit2D hit1 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y - 72.0f), Vector2.up, 150.00f, layerMask);
RaycastHit2D hit2 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y + 85.0f), Vector2.up, 600.00f, layerMask);
RaycastHit2D hit3 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y - 85.0f), Vector2.down, 600.00f, layerMask);
if(!Rayhit1)
{
if(hit1.collider.name == "GameObject")
{
RayHit1 = true; //boolean to true for just 1 frame so that the score does not add more than once
score.value += 30;
}
}
if(!hit1)
{
RayHit1 = false; //reset boolean to false when Raycast returns nothing
}
if(!Rayhit2)
{
if(hit2.collider.name == "GameObject")
{
RayHit2 = true;
score.value += 10;
}
}
if(!hit2)
{
RayHit2 = false;
}
if(!Rayhit3)
{
if(hit3.collider.name == "GameObject")
{
RayHit3 = true;
score.value += 10;
}
}
if(!hit3)
{
RayHit3 = false;
}
}
解决方案
我认为您可能在值 hit1.collider 处有 NullReferenceException
if(hit1.collider.name == "GameObject")
{
RayHit1 = true; //boolean to true for just 1 frame so that the score does not count add than once
score.value += 30;
}
在读取名称之前尝试检查命中是否发生碰撞:
if(!Rayhit1)
{
if(hit1 && hit1.collider.name == "GameObject")
{
RayHit1 = true; //boolean to true for just 1 frame so that the score does not count add than once
score.value += 30;
}
}
推荐阅读
- ios - 使用动态 url 深度链接 iOS
- ios - Actionscript netStream 用 ios 播放 mp4
- apache - 有条件的 apache 重写
- http - 从 webdav 服务器下载文件
- python - openCV:cv2.VideoCapture(0) 和 cv2.VideoCapture(-1) 的问题
- jekyll - 在 Jekyll 中按类别显示语言过滤的帖子
- protractor - 每次在量角器中打开浏览器时如何访问onPrepare中的功能
- python - 将 QMessageBox 设置转移到 Python 中的单独类
- python - PyAudio 在 Raspberry Pi 上引发警告
- excel - Vlookup 用分号分隔的多个值