LoginSignup
2
1

Unity UIでScriptからButtonをSelect状態にする

Posted at

Unity UIのButtonをSelect状態にする方法

EventSystemSelectedGameObjectに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以外でも、ToggleInputFieldなど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);
    }
}

参考

2
1
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
2
1