I just started using events, and got stuck a little. I have a problem with the following code:
class InputHandler
{
public delegate void Shooting();
public static event Shooting OnShoot;
void Update()
{
if( fireButtonPressed)
OnShoot();
}
// Rest of the class.
}
class Weapon
{
void Shoot()
{
//Do the shooting.
}
void OnEnable()
{
InputHandler.OnShoot += shooting;
}
void OnDisable()
{
InputHandler.OnShoot -= shooting;
}
}
class UI
{
void UpdateBulletsCount(int bulletsLeft, int magSize)
{
//Update the UI.
}
void OnEnable()
{
InputHandler.OnShoot += UpdateBulletsCount; // clearly can't do that.
}
void OnDisable()
{
InputHandler.OnShoot -= UpdateBulletsCount;
}
}
My UI class has a method to update the bullet count when you fire, reload or change the weapon. As you can clearly see, it takes in different parameters. This allows me to change the UpdateBulletsCount()
to accept no parameters, and find the weapons info through GetComponent
or Find
, in order to update UI
.
However, then the UI
class will depend on the Weapon
class, which breaks the separation of classes and components that I am trying to achieve. Is there any way to use events without breaking class and component separation?