Skip to content

Instantly share code, notes, and snippets.

@BigHandInSky
Last active January 13, 2021 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BigHandInSky/922e82c51e9d0f4585864b392ddf46b4 to your computer and use it in GitHub Desktop.
Save BigHandInSky/922e82c51e9d0f4585864b392ddf46b4 to your computer and use it in GitHub Desktop.
Simple UI Navigation Scripts: These 3 combine to form a pretty solid gamepad-supporting UI
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace _project.ui
{
public class SetFocusByPointer : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
private bool _isSelectedByEventSystem => EventSystem.current.currentSelectedGameObject == gameObject;
public void OnPointerEnter( PointerEventData eventData )
{
if(!_isSelectedByEventSystem)
EventSystem.current.SetSelectedGameObject( gameObject );
}
public void OnPointerExit( PointerEventData eventData )
{
if(_isSelectedByEventSystem)
EventSystem.current.SetSelectedGameObject( null );
}
}
}
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
namespace _project.ui
{
public class SetFocusedIfNothingSelected : MonoBehaviour
{
private InputAction _navigateAction;
private bool _anythingSelected => EventSystem.current.currentSelectedGameObject != null;
private void Update()
{
if ( _navigateAction == null )
{
var i = PlayerInput.GetPlayerByIndex( 0 );
if ( i != null )
{
_navigateAction = i.actions.FindAction( "Navigate" );
}
}
else if ( !_anythingSelected && _navigateAction.ReadValue<Vector2>().magnitude > 0 )
{
//Debug.Log( $"Focuser[{name}] acting" );
EventSystem.current.SetSelectedGameObject( gameObject );
}
}
}
}
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace _project.ui
{
public class SetFocusedOnEnable : MonoBehaviour
{
public Selectable selectable;
private void Reset()
{
selectable = GetComponentInChildren<Selectable>();
}
private void OnEnable()
{
//EventSystem.current.SetSelectedGameObject( selectable.gameObject, null );
StartCoroutine( SelectContinueButtonLater() );
}
IEnumerator SelectContinueButtonLater()
{
yield return null;
EventSystem.current.SetSelectedGameObject(null);
EventSystem.current.SetSelectedGameObject(selectable.gameObject);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment