Skip to content

Instantly share code, notes, and snippets.

@rubit0
Last active March 22, 2016 20:46
Show Gist options
  • Save rubit0/fa3fbecb4e6cfcab48b3 to your computer and use it in GitHub Desktop.
Save rubit0/fa3fbecb4e6cfcab48b3 to your computer and use it in GitHub Desktop.
Attach this Script to any UI Element on your Canvas to make it self auto selected when it get's enabled. Useful for Gamepad only games!
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections;
[AddComponentMenu("Helpers/UI/Self Auto Selected")]
[RequireComponent(typeof(Selectable))]
public class UIAutoSelectSelf : MonoBehaviour
{
public bool AutoSelectOnEnable = true;
private EventSystem _sceneEventSystem;
void Awake()
{
_sceneEventSystem = FindObjectOfType<EventSystem>();
}
void OnEnable()
{
if(AutoSelectOnEnable && _sceneEventSystem)
StartCoroutine(DelayedSelfSelect());
}
IEnumerator DelayedSelfSelect()
{
_sceneEventSystem.SetSelectedGameObject(null, new BaseEventData(EventSystem.current));
yield return null;
_sceneEventSystem.SetSelectedGameObject(this.gameObject, new BaseEventData(EventSystem.current));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment