Danro/Assets/Resources/Scripts/UI/FullscreenToggle.cs

102 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using UnityEngine.InputSystem;
namespace RR.Common.UI
{
public class FullscreenToggle : MonoBehaviour
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void Bootstrap()
{
var go = new GameObject("FullscreenToggle");
go.AddComponent<FullscreenToggle>();
DontDestroyOnLoad(go);
}
private InputAction _action;
private bool _ownsAction = false;
private void OnEnable()
{
// 1) Пытаемся найти PlayerInput и экшен "Fullscreen" в его Asset
var playerInput = FindAnyPlayerInput();
var fromAsset = playerInput && playerInput.actions
? playerInput.actions.FindAction("Fullscreen", throwIfNotFound: false)
: null;
if (fromAsset != null)
{
_action = fromAsset;
_action.performed += OnFullscreenPerformed;
_action.Enable(); // на случай если был выключен
_ownsAction = false;
}
else
{
// 2) Нет PlayerInput/экшена — создаём локальный InputAction целиком кодом
_action = new InputAction(name: "Fullscreen", type: InputActionType.Button);
_action.AddBinding("<Keyboard>/f11");
// Alt+Enter (левый Alt)
var comp1 = _action.AddCompositeBinding("OneModifier");
comp1.With("modifier", "<Keyboard>/leftAlt");
comp1.With("binding", "<Keyboard>/enter");
// Alt+Enter (правый Alt)
var comp2 = _action.AddCompositeBinding("OneModifier");
comp2.With("modifier", "<Keyboard>/rightAlt");
comp2.With("binding", "<Keyboard>/enter");
_action.performed += OnFullscreenPerformed;
_action.Enable();
_ownsAction = true;
}
}
private void OnDisable()
{
if (_action != null)
{
_action.performed -= OnFullscreenPerformed;
if (_ownsAction) _action.Dispose();
_action = null;
_ownsAction = false;
}
}
private static PlayerInput FindAnyPlayerInput()
{
return FindFirstObjectByType<PlayerInput>();
}
// Если используешь PlayerInput в режиме Send Messages, метод с тем же именем тоже сработает:
// public void OnFullscreen(InputAction.CallbackContext ctx) { if (ctx.performed) Toggle(); }
private void OnFullscreenPerformed(InputAction.CallbackContext ctx)
{
if (ctx.performed) Toggle();
}
private static void Toggle()
{
if (Application.platform == RuntimePlatform.WebGLPlayer) return;
bool fs = !Screen.fullScreen;
Screen.fullScreenMode = fs ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed;
if (fs)
{
Screen.SetResolution(Display.main.systemWidth, Display.main.systemHeight, true);
Screen.fullScreen = true;
}
else
{
int w = Mathf.RoundToInt(Display.main.systemWidth * 0.5f);
int h = Mathf.RoundToInt(Display.main.systemHeight * 0.5f);
Screen.fullScreen = false;
Screen.SetResolution(w, h, false);
}
}
}
}