If vs Switch

I have following code, how do I convert it into switch and would it make any difference in performance.

As AnimatorStateInfo doesn’t have value for name, just IsName(string) check I can’t think of simple way to make it with switch-case. It might be somewhat more efficient in same cases, but difference is really small if you fix your current code to be proper if-elseif-else.

Currently what your code does it will check every if-clause one by one even if the first one is true it will still check all that come after it. As only one can be true at once first one should be if() and all that come after that should be if else().

For example:

if (currentState.IsName ("Run"))
{
    soldier.velocity = new Vector3 (0,0, -moveSpeed);
}
else if (currentState.IsName ("StrafeLeft")) 
{
    soldier.velocity = new Vector3 (-moveSpeed,0,0);
}
else if (currentState.IsName ("StrafeRight")) 
{
    soldier.velocity = new Vector3 (moveSpeed,0,0);
}

This code would first check if the name is “Run” and if it is true it will skip all the rest. Only if it is false it will continue to check the next one. First one will be fastest as there is only one check so you could also do small optimization by ordering the list. Technically settings the most heaviest option as first would give most stable framerates, but in practice you probably wont even notice the difference.

switch(myString)
{
case “Test”: break;
case “Other string”: break;
}

As for the performances, I’ll let you do your tests. However, I would highly recommend that you keep the hashed name of each state you want to test using Animator.StringToHash and used the hashed integers as based of the switch. It would clearly be the most efficient way.