Checking multiple if variables

Hello all,

Novice coder here so apologies if this has been answered, however I did not know how to word it and could not find it by searching.

Staying within the coder’s credo, I want to minimize my repeating code as much as possible so instead of writing multiple if statements to check for various differing variables I was hoping there was a shorthand that would read something like this:

If (gameobject.name ==
name1{
destroy it}
name2{
move it}
name3{
rotate it}
)

The functions are irrelevant as this is just an example, and I’m sure this involves looping in some manner.

Thank you forums,
Alex V

Normaly looking for different names you can make

If(gameObject.name == "go1") {

} else if (gameObject.name == "go2") {

}

But without knowing how the rest of your code looks like, where your want to put this code or how your gameobjects are named i can’t suggest any other way.

You are looking for a switch statement. This can also be expressed as a series of if else statements.

However, this kind of code is an example of a code smell. Object oriented programming would encourage behavior through polymorphism possibly by replacing typecodes with subclassing or the state/strategy pattern

switch (gameObject.name)
{
//When name is "Name1", destroy
      case "Name1":
             Destroy(gameObject);
             break;
//when name is "Name2", move
      case "Name2":
             transform.Translate(transform.forward);
             break;
//else do nothing
      default:
             break;
}


https://unity3d.com/learn/tutorials/modules/beginner/scripting/switch

2 Likes