72 lines
2.0 KiB
C#
72 lines
2.0 KiB
C#
#nullable enable
|
|
|
|
using System;
|
|
using UnityEngine;
|
|
|
|
namespace ShrinkEventBus
|
|
{
|
|
/// <summary>
|
|
/// Optional Unity lifecycle host for generated event bindings. It does not require
|
|
/// the target component to inherit from an SDK base class.
|
|
/// </summary>
|
|
[DisallowMultipleComponent]
|
|
public sealed class ShrinkMonoEventScope : MonoBehaviour
|
|
{
|
|
[SerializeField] private string bus = "game";
|
|
[SerializeField] private bool includeChildren;
|
|
private IDisposable? _binding;
|
|
private ShrinkEventBinding? _bindingGroup;
|
|
|
|
public string BusId
|
|
{
|
|
get => bus;
|
|
set => bus = value ?? string.Empty;
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
RefreshBindings();
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
ReleaseBindings();
|
|
}
|
|
|
|
public void RefreshBindings()
|
|
{
|
|
ReleaseBindings();
|
|
var key = ShrinkBusKey.Parse(bus);
|
|
if (!EventBus.TryGetBus(key, out var targetBus))
|
|
targetBus = EventBus.GetOrCreateBus(key, ShrinkBusOptions.MainThread());
|
|
|
|
var components = includeChildren
|
|
? GetComponentsInChildren<MonoBehaviour>(true)
|
|
: GetComponents<MonoBehaviour>();
|
|
for (var i = 0; i < components.Length; i++)
|
|
TryAttach(components[i], targetBus);
|
|
}
|
|
|
|
public void ReleaseBindings()
|
|
{
|
|
_binding?.Dispose();
|
|
_binding = null;
|
|
_bindingGroup = null;
|
|
}
|
|
|
|
private void TryAttach(MonoBehaviour target, IShrinkEventBus targetBus)
|
|
{
|
|
if (target == null || ReferenceEquals(target, this))
|
|
return;
|
|
if (target is not IShrinkGeneratedSubscriber)
|
|
return;
|
|
|
|
var binding = targetBus.Attach(target);
|
|
if (_bindingGroup == null)
|
|
_bindingGroup = new ShrinkEventBinding();
|
|
_bindingGroup.Add(binding);
|
|
_binding = _bindingGroup;
|
|
}
|
|
}
|
|
}
|