Recognising different string inputs for same result (using "or" statements for strings)
Hey there,
What is the most efficient way of using an "or" statement for a string in C#? By that I mean having the game register the same response to a variety of possible player inputs. As an example, I want something like this to occur when the game asks the player to enter what kind of food they like:
if (FoodILike == "Burritos") || (FoodILike == "Tacos") { //Allowing for the player to more organically enter a response
PlayerFood = "Mexican";
Debug.Log("The player likes Mexican Food!");
}
Of course, I could always enter something like:
if (FoodILike == "Burritos") {
PlayerFood = "Mexican";
Debug.Log("The player likes Mexican Food!");
}
if (FoodILike == "Tacos") {
PlayerFood = "Mexican";
Debug.Log("The player likes Mexican Food!");
}
But feels way too clunky, especially as I'm hoping to have a broader pool of possible inputs to draw from.
Cheers!
Answer by TheMazinTar · Jun 14, 2016 at 04:56 AM
Is there a particular reason you don't want to just use "if" and "else if" statements? The first example that you gave should do the trick just fine.
If you're looking for an alternative, though, you may want to consider switch statements. I haven't used them a whole lot myself, but I believe this would compile fine:
string FoodLike = "Burritos";
switch (FoodLike)
{
case "Burritos":
case "Tacos":
PlayerFood = "Mexican";
Debug.Log("The player likes Mexican Food!");
break;
case "Lasagna":
PlayerFood = "Italian";
break;
}
Thank you for your help! Turns out I made a syntactical error which is why it was broken, so all is good. However, the switch statement thing looks interesting and could be useful as well. Again, cheers!
Your answer
Follow this Question
Related Questions
how to divide a string with number at a certain amount? 2 Answers
naming days of the week, how to iterate through strings? 2 Answers
ui.text string matching doesn't work 0 Answers
checking numbers in strings 2 Answers
Making a in editor public writing prompt 0 Answers