LoginSignup
9
9

More than 5 years have passed since last update.

クリックしたオブジェクトの名前を取得

Last updated at Posted at 2015-06-14

マウスカーソルでオブジェクトを選択するにはRaycastを用いる。

以下のスクリプトをメインカメラにアタッチして、名前を取得したいオブジェクトにColliderを設定しておく。


public class Touch : MonoBehaviour {
  // rayが届く範囲
  public float distance = 100f;
  void Update () {
    // 左クリックを取得
    if (Input.GetMouseButtonDown(0)) {
      // クリックしたスクリーン座標をrayに変換
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      // Rayの当たったオブジェクトの情報を格納する
      RaycastHit hit = new RaycastHit();
      // オブジェクトにrayが当たった時
      if (Physics.Raycast(ray, out hit, distance)) {
        // rayが当たったオブジェクトの名前を取得
        string objectName = hit.collider.gameObject.name;
        Debug.Log(objectName);
      }
    }
  }
}
9
9
0

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
9
9