
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にプロジェクトファイル上げたほうがいいよね...
いいなと思ったら応援しよう!
