LoginSignup
5

More than 5 years have passed since last update.

【Unity5】ゲームパッドが接続されているかどうかをスクリプトで確認する

Posted at

概要

Unity5でゲームパッドが接続されているかをスクリプトで確認したかったので、
その方法をまとめておきます。

スクリプト

まず、以下が結果となるサンプルのスクリプトです。

sample.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sample : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        // 接続されているコントローラの名前を調べる
        var controllerNames = Input.GetJoystickNames();

        // 一台もコントローラが接続されていなければエラー
        if( controllerNames[0] == "" ) Debug.Log("Error");
    }

}

手法

直接「ゲームパッドが接続されているか」を確認できる関数やプロパティは見つけられなかったので、
代わりに Input.GetJoystickNames() という現在接続されているゲームパッドの名前を取得できるメソッドを利用しました。
Input.GetJoystickNames() で接続されているゲームパッドの名前を取得し、
配列の先頭の文字列が空であれば「一台も接続されていない」と判断しています。

ちなみに、 Input.GetJoystickNames() で取得した配列の大きさを取得すれば、接続されているゲームパッドの数も求められますね。
:warning:ただしゲームパッドがゼロ台でも、配列は1の大きさを持つのでご注意を。)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5