I’ve build a little prototype game. Each player can shoot projectile and can’t shoot again until it explodes (out of screen bounds, collision, etc). I’m using Observer pattern so player subscribes to projectile instance destruction delegate and changes its state when projectile destroyed. My question is: how do i unsubscribe from projectile that being destroyed?
public class Projectile : MonoBehaviour
{
[SerializeField] private float _speed = 5f;
private Rigidbody2D _rigidbody2D;
public event Action OnDestroy;
private void Awake()
{
_rigidbody2D = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
_rigidbody2D.MovePosition(_rigidbody2D.position + (Vector2)_rigidbody2D.transform.up * _speed * Time.fixedDeltaTime);
}
private void OnBecameInvisible()
{
OnDestroy?.Invoke();
Destroy(gameObject);
}
}
public class Player : MonoBehaviour
{
[SerializeField] private Projectile _projectilePrefab;
private bool _canShoot = true;
private void Update()
{
ShootHandler();
}
private void ShootHandler()
{
if (_canShoot == false)
return;
if (Input.GetButtonDown(KeyCode.Space)) {
_canShoot = false;
Projectile projectile = Instantiate(_projectilePrefab, transform.position, Quaternion.identity);
projectile.OnDestroy += ProjectileDestoyed;
}
}
private void ProjectileDestoyed()
{
_canShoot = true;
}
}