Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

if statement question

Discussion in 'Scripting' started by Loff, Jun 25, 2015.

  1. Loff

    Loff

    Joined:
    Dec 3, 2012
    Posts:
    81
    hey,

    I was wondering if "IF statement" had a short way of this doing:

    Code (CSharp):
    1. if ((playerCurrentPosisition >= 0 && 4 > playerCurrentPosisition) || (playerCurrentPosisition == 11) || (playerCurrentPosisition == 12))
    Do if statement have a easy way to do this, for example writting
    Code (CSharp):
    1. if (playerCurrentPosisition == 0,1,2,4,11,12) {
    2.  
    3. }

    - Thanks
     
  2. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,302
    Maybe easier to use a switch case

    Code (csharp):
    1.  
    2. switch(playerCurrentPosisition)
    3. {
    4.    case 0:case 1:case 2:case 4:case 11:case 12:
    5.     // Do Something
    6.     break;
    7.    default:
    8.     // Do Something
    9.     break;
    10. }
    11.  
    You should probably be holding those numbers in a list though, then you can just ask the list if it contains the number
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Refractor it into a helper method.
     
  4. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Not really. If you are just dealing with ints, you could so something like this (though I wouldn't recommend it):
    Code (csharp):
    1. if (new int[] {0, 1, 2, 3, 4, 11, 12}.Contains(playerCurrentPosisition))
    Long if/switch statements are often a good target for the Strategy Pattern. Take a read through this and see if it applies to your situation.

    http://blogs.microsoft.co.il/gilf/2...y-pattern-instead-of-using-switch-statements/
     
    Boz0r likes this.
  5. Loff

    Loff

    Joined:
    Dec 3, 2012
    Posts:
    81
    Cheers for decent replies :)
     
  6. jctz

    jctz

    Joined:
    Aug 14, 2013
    Posts:
    47
    use a bitflag:

    Code (CSharp):
    1. int flags = ( 1 << 0 ) | ( 1 << 1 ) || ( 1 << 2 ) | ( 1 << 3 ) | ( 1 << 4 ) | ( 1 << 11 ) | ( 1 << 12 );
    2.  
    3. if( ( flags & ( 1 << position ) ) != 0 )
    4. {
    5.     ...
    6. }
    (only works if you have fewer than 32 positions)