Danro/Assets/Scripts/Settings/Core/SettingsButtonDispatcher.cs
Danil Iarosh 009152ac5b
Some checks failed
Gitea Actions Demo / Explore-Gitea-Actions (push) Has been cancelled
Added ValueSelectorRow option to int settings
- Добавил новый тип отображения настроек с целочисленным значением
- У этого типа можно настраивать шаг, выглядит приятнее
2026-02-06 16:14:39 +03:00

119 lines
4.3 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 System.Collections.Generic;
using RR.Common.UI;
using UnityEngine;
namespace RR.Common.Settings
{
/// <summary>
/// Диспетчер для связи кнопок настроек с объектами на сцене.
/// Позволяет объектам сцены подписываться на нажатия кнопок по ключу.
/// </summary>
public static class SettingsButtonDispatcher
{
private static readonly Dictionary<string, List<SettingsButtonBinder>> bindings = new();
/// <summary>
/// Регистрирует биндер для указанного ключа кнопки
/// </summary>
public static void Register(string buttonKey, SettingsButtonBinder binder)
{
if (string.IsNullOrWhiteSpace(buttonKey) || binder == null) return;
if (!bindings.TryGetValue(buttonKey, out var list))
{
list = new List<SettingsButtonBinder>();
bindings[buttonKey] = list;
}
if (!list.Contains(binder))
{
list.Add(binder);
}
}
/// <summary>
/// Удаляет биндер для указанного ключа кнопки
/// </summary>
public static void Unregister(string buttonKey, SettingsButtonBinder binder)
{
if (string.IsNullOrWhiteSpace(buttonKey) || binder == null) return;
if (bindings.TryGetValue(buttonKey, out var list))
{
list.Remove(binder);
if (list.Count == 0)
{
bindings.Remove(buttonKey);
}
}
}
/// <summary>
/// Вызывает все зарегистрированные биндеры для указанного ключа кнопки
/// </summary>
/// <returns>True если хотя бы один биндер был вызван</returns>
public static bool Dispatch(string buttonKey)
{
if (string.IsNullOrWhiteSpace(buttonKey))
{
Debug.LogWarning("[SettingsButtonDispatcher] Dispatch called with empty key");
return false;
}
// Пробуем найти в зарегистрированных биндерах
if (bindings.TryGetValue(buttonKey, out var list) && list.Count > 0)
{
return InvokeBinders(list);
}
// Fallback: ищем все биндеры в сцене (включая неактивные)
var allBinders = Object.FindObjectsByType<SettingsButtonBinder>(FindObjectsInactive.Include, FindObjectsSortMode.None);
var matchingBinders = new List<SettingsButtonBinder>();
foreach (var binder in allBinders)
{
if (binder.Key == buttonKey)
{
matchingBinders.Add(binder);
// Регистрируем для будущих вызовов
Register(buttonKey, binder);
}
}
if (matchingBinders.Count > 0)
{
return InvokeBinders(matchingBinders);
}
return false;
}
private static bool InvokeBinders(List<SettingsButtonBinder> binders)
{
bool anyInvoked = false;
// Копируем список чтобы избежать проблем при модификации во время итерации
var copy = new List<SettingsButtonBinder>(binders);
foreach (var binder in copy)
{
if (binder != null)
{
binder.Invoke();
anyInvoked = true;
}
}
return anyInvoked;
}
/// <summary>
/// Очищает все регистрации (вызывать при смене сцены если нужно)
/// </summary>
public static void Clear()
{
bindings.Clear();
}
}
}