見出し画像

Unity で今選択されているオブジェクトを取得したい。

いつものようにプロジェクトファイルはこちら

Unity には EventSystem というものがあり,Button などの UI 部品の選択状況などを管理してくれます。

現在選択中のオブジェクトを取得できると何かと便利なのでサンプルコードを書きました。

シーン中では選択中のボタンの情報を引っこ抜いて,テキストデータを変化させています。

画像

<CurrentSelected.cs>

using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class CurrentSelected : MonoBehaviour {

    // eventSystemを取得するための変数宣言
    [SerializeField] EventSystem eventSystem;

    [SerializeField] Text text;
    GameObject selectedObj;

	// Update is called once per frame
	void Update () {

        // クリックされたタイミングで判定する
        if (Input.GetMouseButton(0))
        {
            // TryCatch文でNull回避
            try
            {
                // 子供のコンポーネントにアクセスしたいのでいったん変数に格納
                selectedObj = eventSystem.currentSelectedGameObject.gameObject;
                // ボタンの子供のTextコンポーネントからtextデータを取得
                text.text = selectedObj.GetComponentInChildren<Text>().text ;
            }
            // 例外処理的なやつ
            catch (NullReferenceException ex)
            {
                // なにも選択されない場合に
                text.text = "どれや";
            }
        }
	}
}

Hierarchy などはこんな感じ

画像

解説

キモは eventSystem.currentSelectedGameObject です。
シーン内にあるEventSystemを参照すれば .currentSelecctedGameObject で簡単に取得可能です。

ほかに説明することは特にありません。

単純にテキストの内容を変更したいだけならもっと楽で軽い実装方法があると思います。ボタンのクリックイベントを使うとか。

質問などはコメントに!!

GitHubにプロジェクトファイル上げたほうがいいよね...

最後まで読んでもらえて嬉しいです。よければフォローもお待ちしています。サポートは記事を書くときのコーヒーになります。

ピックアップされています

UnityTips

  • 8本

コメント

ログイン または 会員登録 するとコメントできます。
Unity で今選択されているオブジェクトを取得したい。|でたらめ荘のこんぶ
word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word

mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1