[英]How to use multiple boolean conditions in a single if statement?
我正在制作一个谜题,玩家必须将巨石推到相应的按钮/压力板上。 我在原型的硬代码中使用布尔值,但发现自己在布尔值之间应该使用什么标点符号方面遇到困难? && 和 || 没用。
感谢您愿意提供帮助。
请忽略混乱,我需要帮助的是“if”语句中底部的 public void OpenDoor,即 trigger_1 和 trigger_2 之间的那个(用什么替换逗号)。 任何改进代码的建议也很受欢迎。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerAllButtons : UsedOnceFieldButton
{
bool trigger_1 = false;
bool trigger_2 = false;
//bool trigger_3 = false;
//bool trigger_4 = false;
//bool trigger_5 = false;
//bool trigger_6 = false;
public string button_1 = "Button 1";
public string button_2 = "Button 2";
//public string button_3 = "Button 3";
//public string button_4 = "Button 4";
//public string button_5 = "Button 5";
//public string button_6 = "Button 6";
public string boulder_1 = "Boulder 1";
public string boulder_2 = "Boulder 2";
//public string boulder_3 = "Boulder 3";
//public string boulder_4 = "Boulder 4";
//public string boulder_5 = "Boulder 5";
//public string boulder_6 = "Boulder 6";
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag(button_1) && other.CompareTag(boulder_1))
{
trigger_1 = true;
}
if (other.CompareTag(button_2) && other.CompareTag(boulder_2))
{
trigger_2 = true;
}
// if (other.CompareTag(button_3) && other.CompareTag(boulder_3))
// {
// trigger_3 = true;
// }
// if (other.CompareTag(button_4) && other.CompareTag(boulder_4))
// {
// trigger_4 = true;
// }
// if (other.CompareTag(button_5) && other.CompareTag(boulder_5))
// {
// trigger_5 = true;
// }
// if (other.CompareTag(button_6) && other.CompareTag(boulder_6))
// {
// trigger_6 = true;
// }
}
public void OpenDoor()
{
if (trigger_1 = true, trigger_2 = true) //&& (trigger_3 = true) && (trigger_4 = true) && (trigger_5 = true) && (trigger_6 = true))
{
UsedButton();
}
}
}
您混淆了赋值=
和比较==
运算符。 这就是为什么您认为 boolean 运算符&&
和||
不工作。
// this is wrong
// trigger_1 and trigger_2 get true ->assigned<- before && is evaluated
// thus the "if" is always true
if (trigger_1 = true && trigger_2 = true)
// should be like this
// trigger_1 and trigger_2 are only ->compared<- to true before && is evaluated
// this can give "if (false && true)" for example
if (trigger_1 == true && trigger_2 == true)
同样的逻辑适用于其他 boolean 运营商(如||
)。 在错误的 if 语句中,您不小心更改了bool
的值。 旁注:写if (trigger_1 && trigger_2)
就足够了,无论如何它们都是bool
。
据我了解,您需要用适当的运算符替换开门的逗号有两个常见的运算符 OR ||, AND && 如果只有一个 bool 为真,则条件将返回 true,只有当两个 bool 都为 false 时才返回 False对于 AND 运算符,两个 bool 都需要在其他条件下为 true 才能返回 true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.