// Copyright (c) Pixel Crushers. All rights reserved.
using UnityEngine;
namespace PixelCrushers
{
public static class UIUtility
{
///
/// Ensures that the scene has an EventSystem.
///
/// If needing to add an EventSystem, show this message.
public static void RequireEventSystem(string message = null)
{
var eventSystem = PixelCrushers.GameObjectUtility.FindFirstObjectByType();
if (eventSystem == null)
{
if (message != null) Debug.LogWarning(message);
eventSystem = new GameObject("EventSystem").AddComponent();
#if USE_NEW_INPUT
var inputModule = eventSystem.gameObject.AddComponent();
#else
var inputModule = eventSystem.gameObject.AddComponent();
#if !UNITY_2020_1_OR_NEWER
inputModule.forceModuleActive = true;
#endif
#endif
}
}
///
/// Sets the EventSystem to use for all IEventSystemUsers in a hierarchy.
///
public static void SetEventSystemInChildren(Transform t, UnityEngine.EventSystems.EventSystem eventSystem)
{
if (t == null) return;
var eventSystemUser = t.GetComponent();
if (eventSystemUser != null) eventSystemUser.eventSystem = eventSystem;
foreach (Transform child in t)
{
SetEventSystemInChildren(child, eventSystem);
}
}
public static int GetAnimatorNameHash(AnimatorStateInfo animatorStateInfo)
{
return animatorStateInfo.fullPathHash;
}
///
/// Selects a Selectable UI element and visually shows it as selected.
///
///
///
public static void Select(UnityEngine.UI.Selectable selectable, bool allowStealFocus = true,
UnityEngine.EventSystems.EventSystem eventSystem = null)
{
var currentEventSystem = (eventSystem != null) ? eventSystem : UnityEngine.EventSystems.EventSystem.current;
if (currentEventSystem == null || selectable == null) return;
if (currentEventSystem.alreadySelecting) return;
if (currentEventSystem.currentSelectedGameObject == null || allowStealFocus)
{
UnityEngine.EventSystems.EventSystem.current = currentEventSystem;
currentEventSystem.SetSelectedGameObject(selectable.gameObject);
selectable.Select();
selectable.OnSelect(null);
}
}
public static Font GetDefaultFont()
{
var majorVersion = SafeConvert.ToInt(Application.unityVersion.Split('.')[0]);
var fontName = (majorVersion >= 2022) ? "LegacyRuntime.ttf" : "Arial.ttf";
return Resources.GetBuiltinResource(fontName);
}
}
}