Switch statements?

Can we use these in UnityScript, or do we have to just use loads of “If” statements?

If we can use 'em, how do we use 'em?

Thanks, in advance, for any info! :slight_smile:

Well of course you can:

var n : int = 3;
	
switch (n)
{
case 1: Debug.Log("1"); break;
case 2: Debug.Log("2"); break;
case 3: Debug.Log("3"); break;
}

Odd. My code reads like this:

switch ( n )
{
   case 0:
   {
      if ( 1 )
      {
          Debug.Log("1");
      }
      break;
   }
   case 1:
   {
      Debug.Log("2");
      break;
   }
}

And I get errors!

BCE0044: expecting :, found ‘{’.

The error points at the curly bracket after the “If” statement - what’s that all about?

I think it’s the curly brackets after the case statement. Try this:

switch ( n )
{
   case 0:

      if ( 1 )
      {
          Debug.Log("1");
      }
      break;

   case 1:

      Debug.Log("2");
      break;

}

Nope! Now I get the following error:

UCE0001: ‘;’ expected. Insert a semicolon at the end.

Clicking on the error takes me to the “if” statement line again…! Very confused! :frowning:

Does removing the condition make it compile?
If so, then you probably can’t put if statements into switch/case statements.

I would consider that a bug, so please submit it using the Unity bug reporter. Attach the offending script to the report.

To work around it you could use a helper function:

switch ( n )
{
   case 0:
      LogCond(true, "1");
      break;
   case 1:
      Debug.Log("2");
      break;
}

// .. outside the current function:
function LogCond(condition : boolean, message: object) {
   if(condition) Debug.Log(message);
}

From what I know, numbers cannot be used as conditions, they can in C++, but not here.
When you use a number in a switch, you check in your cases if they equal to your number, but it isn’t a condition itself, which is what your if needs.