Search Unity

Problem with controler detection

Discussion in 'Scripting' started by dudedude123, Aug 10, 2018.

  1. dudedude123

    dudedude123

    Joined:
    Aug 24, 2013
    Posts:
    128
    Im making a setup screen for my sports game. What i want it to do is to enable the controller icon if it detects the controller
    2018-08-05_20h59_12.png
    2018-08-05_20h58_54.png
    Code (CSharp):
    1.     // Use this for initialization
    2.     void Start()
    3.     {
    4.         if (Input.GetJoystickNames()[0] == "true")
    5.         {
    6.             playerOne.SetActive(true);
    7.  
    8.         }
    9.         else
    10.         {
    11.             playerOne.SetActive(false);
    12.         }
    13.  
    14.         if (Input.GetJoystickNames()[1] == "true")
    15.         {
    16.             playerTwo.SetActive(true);
    17.  
    18.         }
    19.         else
    20.         {
    21.             playerTwo.SetActive(false);
    22.         }
    23.     }
    The main problem is that when the player one controller is detected the icon disables and te player two icon is enabled

    2018-08-05_21h01_46.png
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    GetJoystickNames as per the documentation returns a string array of "meaningful names":
    https://docs.unity3d.com/ScriptReference/Input.GetJoystickNames.html

    This line:
    Code (csharp):
    1. if (Input.GetJoystickNames()[0] == "true")
    And this line:
    Code (csharp):
    1. if (Input.GetJoystickNames()[1] == "true")
    Unless you happen to attach a controller whose driver reports its name to be "true", will never be equal to "true".

    Furthermore... these lines of code will throw exceptions if you have run this script and NOT have 2 gamepads attached.