using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TakeDamage : MonoBehaviour
{
public HealthSystem Hsys;
public PlayerController PCont;
private Collider2D collision;
private bool Trigger;
public int DamageFromTraps;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag.Equals("Trap"))
{
Trigger = true;
DamageCondition();
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag.Equals("Trap"))
{
Trigger = false;
DamageCondition();
}
}
private void DamageCondition()
{
if (Trigger == true)
{
StartCoroutine(Spikes());
}
else if (Trigger == false)
{
StopCoroutine(Spikes());
Debug.Log("Корутина остановлена");
}
}
IEnumerator Spikes()
{
while (Hsys.health > 0)
{
Hsys.health -= DamageFromTraps;
yield return new WaitForSeconds(2f);
}
}
}
Hsys
PCont
TakeDamage
DamageCondition
namespace Coroutines
{
public interface IHealth
{
bool IsOver { get; }
void Lose(float amount);
void Restore(float amount);
}
}
using System;
using UnityEngine;
namespace Coroutines
{
public class Health : IHealth
{
private readonly float _max;
private readonly float _min;
private float _current;
public Health(float max, float min = 0)
{
_max = max;
_min = min;
_current = _max;
}
public bool IsOver => _current <= _min;
public void Lose(float amount)
{
if (amount <= 0) throw new ArgumentException();
SetCurrent(_current - amount);
}
public void Restore(float amount)
{
if (amount <= 0) throw new ArgumentException();
SetCurrent(_current + amount);
}
private void SetCurrent(float amount)
{
_current = Mathf.Clamp(amount, _min, _max);
}
}
}
namespace Coroutines
{
public interface IDamageable
{
bool IsDead { get; }
void ApplyDamage(float amount);
}
}
using UnityEngine;
namespace Coroutines
{
public class Character : MonoBehaviour, IDamageable
{
[SerializeField] private float _maxHp = 100f;
private IHealth _health;
public bool IsDead => _health.IsOver;
private void Awake()
{
_health = new Health(_maxHp);
}
public void ApplyDamage(float amount) => _health.Lose(amount);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Coroutines
{
public class Trap : MonoBehaviour
{
[SerializeField] private float _damage = 10f;
[SerializeField] private float _delay = 2f;
private readonly Dictionary<IDamageable, Coroutine> _targets = new();
private void OnTriggerEnter2D(Collider2D other)
{
if (other.TryGetComponent(out IDamageable damageable))
{
var coroutine = StartCoroutine(Damaging(damageable));
_targets.Add(damageable, coroutine);
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.TryGetComponent(out IDamageable damageable))
{
var coroutine = _targets[damageable];
StopCoroutine(coroutine);
_targets.Remove(damageable);
}
}
private IEnumerator Damaging(IDamageable target)
{
while (target.IsDead == false)
{
target.ApplyDamage(_damage);
yield return new WaitForSeconds(_delay);
}
}
}
}