Unity Action decouple classes

1 week ago 11
ARTICLE AD BOX

I'm learning Unity to know how to avoid dependencies. I have these two classes, one that generates an event:

public class ClickController : MonoBehaviour { public static event Action<ClickController> OnClickControllerEvent; // new private void Update() { if (Input.GetMouseButtonDown(0)) OnLeftClick(); } private void OnLeftClick() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Debug.Log("The cube was clicked! Notifying subscribers!"); if (OnClickControllerEvent != null) // new OnClickControllerEvent(this); } } }

And another one that listens to that event:

public class HealthController : MonoBehaviour { [SerializeField] private int minHealth = 0; [SerializeField] private int maxHealth = 100; private int health = 100; private void OnEnable() // new { ClickController.OnClickControllerEvent += TakeDamage; } private void OnDisable() // new { ClickController.OnClickControllerEvent -= TakeDamage; } private void TakeDamage(ClickController clickController) // changed { health -= 10; if (health <= 0) Debug.Log("I'm dead now! :("); } }

In this example, the class HealthController needs to know the class ClickController:

ClickController.OnClickControllerEvent += TakeDamage;

To avoid this, I have tried to use an Interface:

using System; interface IClickInterface { public static event Action OnClickControllerEvent; }

But interfaces don't allow static members.

Is it OK to let class HealthController knows class ClickController?

Or, is there another way to do it?

Read Entire Article