Search Unity

Array od KeyCode

Discussion in 'Getting Started' started by darthachill, Mar 12, 2015.

  1. darthachill

    darthachill

    Joined:
    Jan 25, 2015
    Posts:
    27
    I create script, where Player can Press Key(0-9) and chose Weapon. Is there any way to do this conditions in one loop using Array?
    Code (CSharp):
    1.  
    2.             if (Input.GetKey(KeyCode.Alpha1))
    3.             {
    4.  
    5.             } /// Alpha1 Alpha2...   ...Alpha9
    6.             else if (Input.GetKey(KeyCode.Alpha9))
    7.             {
    8.  
    9.             }
    Something like that:
    Code (CSharp):
    1.         for (int i=0; i< maxWeapons; i++)
    2.         {
    3.             if (Input.GetKey(KeyCode.Array[i]))
    4.             {
    5.  
    6.             } /// Alpha1 Alpha2...   ...Alpha9
    7.             else if (Input.GetKey(KeyCode.Array[i]))
    8.             {
    9.  
    10.             }
    11.         }
    But I don't know what Type Array I need here
    Thx for answers :)
     
  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    I believe you're on the right track. Try something like this.
    Code (CSharp):
    1. private int[] weaponSelections = new int[] {0,1,2,3,4,5,6,7,8,9};
    2.  
    3. public void Update() {
    4.     if (Input.anyKeyDown) {
    5.         for (int i = 0; i < weaponSelections.Length; i += 1) {
    6.             if (Input.GetKeyDown(i.ToString())) {
    7.                 // Switch weapon code here
    8.                 ChangeToWeapon(i);
    9.             }
    10.         }
    11.     }
    12. }
     
    darthachill likes this.
  3. darthachill

    darthachill

    Joined:
    Jan 25, 2015
    Posts:
    27
    Thx you for answer. I was thinking about something like that, but In this case I need to set Name in Projects Settings-> Input, It isn't a problem, but I wonder, if it's possible to do it with using KeyCode.Array
     
  4. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    Ah, yes, that's planning ahead. Hmm...