Search code examples
if-statementunity-game-engineunityscript

Why wont this IF statement work in Unity?


Okay I have a problem. I am using an IF statement. It seems to not run like it should. It works fine without the || condition, but with the || it seems to just pull the text under and not run the 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;
   }
   }

If i remove the ||"Illuminati" it works great... but like this it assigns fateText.text to "We run the entire world." and not the myRandomString

EDIT REPORT: Okay, the .ToLower() worked great now I am running into a problem where when I add multiple IFs it just bypasses the IFs and just runs the ELSE... any ideas?

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;
 }
 }

Solution

  • The condition must be :

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

    Otherwise, you can set to lower all the text so as to be case-independant :

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

    An even better way to compare strings is to use the Equals function (C# only though)

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

    EDIT further to your EDIT:

    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;
    }