为什么这个IF语句不能在Unity中运行?

时间:2017-02-07 18:14:56

标签: if-statement unity3d unityscript

好的,我有问题。我正在使用IF声明。它似乎不应该像它应该的那样运行。没有||它工作正常条件,但与||它似乎只是拉下文本而不是运行ELSE ......

var fateText : UI.Text;
var inputText : UI.Text;


 function fateBall () {
        if(inputText.text == "illuminati"||"Illuminati"){
            fateText.text = "We run the entire world. Join us!";
    }else{
  var myRandomString : String = RandomWordString(1);
 fateText.text = myRandomString;
   }
   }

如果我删除了||“Illuminati”它很有效......但是就像这样它将fateText.text指定给“我们运行整个世界”。而不是myRandomString

编辑报告:好的,.ToLower()工作得很好现在我遇到了一个问题,当我添加多个IF时,它只是绕过IF并运行ELSE ...任何想法?

function fateBall () {
    if(inputText.text.ToLower() == "illuminati"){
            fateText.text = "We run the entire world. Join us!";}
     if(inputText.text.ToLower() == "satan"){
                fateText.text = "Lucifer is the Light Bringer. He leads us           against God!";}
     if(inputText.text.ToLower() == "devil"){
            fateText.text = "Lucifer is the Light Bringer. He leads us     against God!";}
    if(inputText.text.ToLower() == "lucifer"){
            fateText.text = "Lucifer is the Light Bringer. He leads us against God!";}

            else{
 var myRandomString : String = RandomWordString(1);
    fateText.text = myRandomString;
 }
 }

3 个答案:

答案 0 :(得分:2)

条件必须是:

if(inputText.text == "illuminati" || inputText.text == "Illuminati")

否则,您可以设置为降低所有文本以便与案例无关:

if(inputText.text.ToLower() == "illuminati")

比较字符串的更好方法是使用Equals函数(仅限C#

if( String.Equals( inputText.text, "illuminati", System.StringComparison.InvariantCultureIgnoreCase)

进一步编辑您的编辑:

string lowerText = inputText.text.ToLower() ;

if(lowerText == "illuminati")
{
    fateText.text = "We run the entire world. Join us!";
}
else if(lowerText == "satan")
{
    fateText.text = "Lucifer is the Light Bringer. He leads us           against God!";
}
else if(lowerText == "devil")
{
    fateText.text = "Lucifer is the Light Bringer. He leads us     against God!";
}
else if(lowerText == "lucifer")
{
    fateText.text = "Lucifer is the Light Bringer. He leads us against God!";
}
else
{
    var myRandomString : String = RandomWordString(1);
    fateText.text = myRandomString;
}

答案 1 :(得分:1)

尝试更改条件:

inputText.text == "illuminati"||"Illuminati"

对此:

inputText.text == "illuminati"|| inputText.text =="Illuminati"

我认为你不能把这样的条件束缚住。

此外,您可能只想使用小写函数来简化您的情况。所以我相信你可以做以下事情。

if(inputText.text.ToLower()=="illuminati")

答案 2 :(得分:0)

如果要在一个if语句中检查多个condidtions,请执行以下操作:

if (var1 == condition1 || var2 == condition2){}

这将检查其中一个是否返回true,但您也可以使用以下方法检查多个语句是否为真:

if (var1 == condition1 && var2 == condition2){}