Unity UIのButtonをSelect状態にする方法
EventSystemのSelectedGameObjectにGameObjectを指定することでSelect状態にできる。
EventSystem.current.SetSelectedGameObject(button.gameObject);
たとえば、Start()時にButtonをSelect状態にしたいとき。
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UIClass : MonoBehaviour
{
[SeializeField] private Button button;
private void Start()
{
EventSystem.current.SetSelectedGameObject(button.gameObject);
}
}
Button以外でも、Toggle、InputFieldなどSelectableクラスを継承しているクラスは、この方法でSelect状態にできる。
Start()時に上手くSelect状態にならない時
タイミングで、Buttonオブジェクトがまだ読み込まれていないうちにStart()が呼ばれるとSetSelectedGameObjectがきかないときがある。
その時は、コルーチンで1フレーム待ってから、SetSelectedGameObjectを呼ぶ。
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections;
public class UIClass : MonoBehaviour
{
[SeializeField] private Button button;
private void Start()
{
StartCoroutine("ForceSelect");
}
private IEnumerator ForceSelect()
{
yield return null; // 1フレーム待つ
EventSystem.current.SetSelectedGameObject(button.gameObject);
}
}
参考