using System; using Cysharp.Threading.Tasks; using UnityEngine.UIElements; using IServiceProvider = DanieleMarotta.RiversongCodeShowcase.IServiceProvider; namespace DanieleMarotta.RiversongCodeShowcase { [GameSystemGroup(typeof(UISystemGroup))] public class UIInitializationSystem : GameSystem, IServiceProvider, IInitializable, IDisposable { [InjectService] private GameConfig _config; [InjectService] private ISoundPlayer _soundPlayer; private IUIRoot _uiRoot; private UIService _uiService; private TextFormatHelper _textFormatHelper; public UIInitializationSystem(IServiceLocator serviceLocator) : base(serviceLocator) { } public void RegisterServices(IServiceLocator serviceLocator) { serviceLocator.RegisterService(new UIState()); _uiService = new UIService(); serviceLocator.RegisterService(_uiService); _textFormatHelper = new TextFormatHelper(); serviceLocator.RegisterService(_textFormatHelper); } public async UniTask InitializeAsync() { var uiRootGameObject = await _config.UI.RootPrefab.InstantiateAsync(); _uiRoot = uiRootGameObject.GetComponent(); await _uiRoot.Initialize(_uiService); _uiRoot.ElementClicked += OnElementClicked; _uiService.UIRoot = _uiRoot; _uiService.TemplateLibrary = await _config.UI.TemplateLibrary.LoadAssetAsync(); _uiService.TextFormatHelper = _textFormatHelper; } public void Dispose() { _uiRoot.ElementClicked -= OnElementClicked; _uiRoot.Dispose(); } private void OnElementClicked(ClickEvent e) { if (e.target is not VisualElement element) return; if (element.GetFirstAncestorOrSelf(static candidate => candidate is Button || candidate.ClassListContains("ui-click")) == null) return; _soundPlayer.Play(SystemSoundId.UIClick); } } }