using UnityEngine;

public class ControllerDetector : MonoBehaviour
{
    /// <summary>
    /// Checks if a controller is currently connected.
    /// </summary>
    /// <returns>True if a controller is connected, otherwise false.</returns>
    public static bool IsControllerConnected()
    {
        // Check if joystick names array is not empty
        string[] joystickNames = Input.GetJoystickNames();
        if (joystickNames != null && joystickNames.Length > 0)
        {
            foreach (string name in joystickNames)
            {
                if (!string.IsNullOrEmpty(name))
                {
                    // Controller detected
                    return true;
                }
            }
        }

        // Check for specific joystick button input
        for (int i = 0; i < 20; i++) // Check for the first 20 joystick buttons
        {
            if (Input.GetKey(KeyCode.JoystickButton0 + i))
            {
                // Controller detected
                return true;
            }
        }

        // No controller detected
        return false;
    }

    // Example usage:
    void Update()
    {
        // Check controller connection status every frame
        if (IsControllerConnected())
        {
            Debug.Log("Controller is connected!");
        }
        else
        {
            Debug.Log("No controller detected.");
        }
    }
}
