cs
1using System.Collections;
2using System.Linq; // 追加
3using UnityEngine;
4using UnityEngine.EventSystems; // 追加
5using UnityEngine.UI; // 追加
6
7public class Right_click_andPress_theFocusButton : MonoBehaviour
8{
9 public Button FocusButton; //消してよい
10
11
12
13
14 private class SelectionHooker : MonoBehaviour, IDeselectHandler
15 {
16
17 public Right_click_andPress_theFocusButton Restrictor;
18
19
20
21
22
23 public void OnDeselect(BaseEventData eventData)
24 {
25 Restrictor.PreviousSelection = eventData.selectedObject;
26 }
27 }
28
29
30 private GameObject PreviousSelection = null;
31
32
33
34
35 private GameObject[] _selectables;
36
37 private void Awake()
38 {
39 EventSystem.current.SetSelectedGameObject(FocusButton.gameObject); //消してよい
40 // すべての Selectable を取得する
41 var selectableList = (FindObjectsOfType(typeof(Selectable)) as Selectable[]).ToList();
42
43 _selectables = selectableList.Select(x => x.gameObject).ToArray();
44
45 // フォーカス許可オブジェクトに SelectionHooker をアタッチ
46 foreach (var selectable in this._selectables)
47 {
48 var hooker = selectable.AddComponent<SelectionHooker>();
49 hooker.Restrictor = this;
50 }
51
52 // フォーカス制御用コルーチンをスタート
53 StartCoroutine(RestrictSelection());
54 }
55
56
57
58
59 private IEnumerator RestrictSelection()
60 {
61 while (true)
62 {
63 // 別オブジェクトを選択するまで待機
64 yield return new WaitUntil(
65 () => (EventSystem.current != null) && (EventSystem.current.currentSelectedGameObject != PreviousSelection));
66
67 // まだオブジェクトを未選択、または許可リストを選択しているなら何もしない
68 if ((PreviousSelection == null) || _selectables.Contains(EventSystem.current.currentSelectedGameObject))
69 {
70 continue;
71 }
72
73 // 選択しているものがなくなった、または許可していない Selectable を選択した場合は前の選択に戻す
74 EventSystem.current.SetSelectedGameObject(PreviousSelection);
75 Debug.Log("ReSelect");
76
77 if(Input.GetMouseButtonDown(1))
78 {
79 try
80 {
81 Button selectedButton = PreviousSelection.GetComponent<Button>();
82 selectedButton.onClick.Invoke();
83 }
84 catch
85 {
86 Debug.Log("null");
87 }
88 }
89 }
90 }
91
92 public void TestAction() //消してよい
93 {
94 Debug.Log("click");
95 }
96}
だいたいこんな感じです、ネックなのはフォーカスされているボタン以外の場所で右クリックすると、フォーカスが外れてしまうので、フォーカスが外れる前に選択されていたオブジェクトを再フォーカスし、ボタンならOnClickイベントを呼び出すようにしています。
常に何らかがフォーカスされ続けている状態になるので、フォーカスを外したい場合はbool関数を追加して制御するなり、このスクリプト自体を別のスクリプトで非アクティブ化するなりする必要があります。