
Unity
- 25 ответов
- 0 вопросов
28
Вклад в тег
Что я не так делаю с интерфейсами?
namespace Health
{
public interface IHealth
{
void Lose(int amount);
void Restore(int amount);
}
public interface IMutable<out T>
{
T Current { get; }
}
public interface IFinal
{
event Action Over;
}
}
using System;
using UnityEngine;
namespace Health
{
public class Health : IHealth, IFinal, IMutable<int>
{
public event Action Over;
private readonly int _max;
private const int Min = 0;
public Health(int max)
{
_max = max;
Current = _max;
}
public int Current { get; private set; }
public void Lose(int amount)
{
SetCurrent(Current - amount);
}
public void Restore(int amount)
{
SetCurrent(Current + amount);
}
private void SetCurrent(int amount)
{
Current = Mathf.Clamp(amount, Min, _max);
if (Current == Min) Over?.Invoke();
}
}
}
namespace Health
{
public interface IDamageable
{
void ApplyDamage(int amount);
}
}
using UnityEngine;
namespace Health
{
public class Knight : MonoBehaviour, IDamageable
{
[SerializeField] private int _maxHealth = 100;
private Health _health;
private void Awake()
{
_health = new Health(_maxHealth);
}
private void OnEnable()
{
_health.Over += Die;
}
private void OnDisable()
{
_health.Over -= Die;
}
public void ApplyDamage(int amount)
{
_health.Lose(amount);
Debug.Log($"Damaged, hp left - {_health.Current}");
}
private void Die()
{
Debug.Log("Died");
Destroy(gameObject);
}
}
}
using UnityEngine;
namespace Health
{
public class Enemy : MonoBehaviour
{
[SerializeField] private int _damage = 50;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.TryGetComponent(out IDamageable damageable))
{
damageable.ApplyDamage(_damage);
}
}
}
}
соответственно, нет точного понимания, когда именно произойдет изменение свойства Interactable
public class SomeCanvas : MonoBehaviour
{
public event Action<bool> ActiveStateChanged;
[SerializeField] private CanvasGroup _canvasGroup;
public void Activate()
{
SetActiveState(true);
}
public void Deactivate()
{
SetActiveState(false);
}
private void SetActiveState(bool state)
{
if (_canvasGroup.interactable == state) return;
_canvasGroup.interactable = state;
ActiveStateChanged?.Invoke(state);
}
}
public class NotSomeCanvas : MonoBehaviour
{
[SerializeField] private SomeCanvas _someCanvas;
private void OnEnable()
{
_someCanvas.ActiveStateChanged += LogActiveState;
}
private void OnDisable()
{
_someCanvas.ActiveStateChanged -= LogActiveState;
}
private void LogActiveState(bool state)
{
print($"Current state - {state}");
}
}