unity3d Unity和C#中的相等运算符不起作用

92vpleto  于 2023-04-21  发布在  C#
关注(0)|答案(1)|浏览(115)

我刚刚为我的商店系统写了一段代码,一个非常简单的行不起作用:

...
if (dir == "left" && rect.anchoredPosition.x != -217.5f) {...}
...

如果锚定位置.x为 -217.5{} 中的代码仍然会运行。但下面的一些行是这样的:

...
else if(rect.anchoredPosition.x != 217.5f)
...

而且效果很好
后来我把第一行改为:

if (dir == "left")
{
   if (rect.anchoredPosition.x != -217.5f)
     {
         ...
     }
}
...

效果很好就像预期的那样
我检查了几次锚定的位置,所以这不是它的错。我知道 dir 是“left”,所以一个是true,但锚定是 -217.5,所以它应该返回false。
我不知道它为什么会这样做。最后,这并不重要,因为有了两个“如果”语句,它就可以工作了,但我仍然想知道为什么。
谢谢

alen0pnh

alen0pnh1#

你有两个版本的代码。

版本A:

if (dir == "left" && rect.anchoredPosition.x != -217.5f)
{
    rect.anchoredPosition -= new Vector2(435f, 0f);
}
else if(rect.anchoredPosition.x != 217.5f)
{
    rect.anchoredPosition +=new Vector2(435f, 0f);
}

版本B:

if (dir == "left")
{
    if (rect.anchoredPosition.x != -217.5f)
    {
        rect.anchoredPosition -= new Vector2(435f, 0f);
    }
}
else if(rect.anchoredPosition.x != 217.5f)
{
    rect.anchoredPosition +=new Vector2(435f, 0f);
}

它们在逻辑上是不同的。
例如rect.anchoredPosition.x = -217.5fdir = "left"
在版本A中,第一个if没有被命中,但是第二个被命中了,所以在那之后rect.anchoredPosition.x将被更改为217.5f。我猜这就是为什么你认为它仍然运行。
在版本B中,第一个if被命中,但内部的if没有被命中,没有任何变化。

相关问题