You could also use the not Unity specific Action
delegates. I like to use a static class for that but you could as well implement it in one of your existing classes (as long as you use static
members and methods)
E.g.
public static class MyEvents
{
public static event Action SomeEvent;
public static void InvokeSomeEvent()
{
// Make sure event is only invoked if someone is listening
if (SomeEvent == null) return;
SomeEvent.Invoke();
}
}
This makes your classes completely independent (well, ok they share the MyEvents class) and easy to modularize.
In script C
add a "listener" e.g.
private void Start()
{
// It is save to remove a listener also if it wasn't there yet
// This makes sure you are not listening twice by accident
MyEvents.SomeEvent -= OnSomeEvent;
// Add the listener for that event
MyEvents.SomeEvent += OnSomeEvent;
}
private void OnSomeEvent ()
{
// Do something if SomeEvent is invoked
}
Then somewhere in script B
just call
MyEvents.InvokeSomeEvent();
So class B
doesn't have to know or care who listens for that event; it just invokes it and cares for it's own business.
On the other side C
or (any other class where you add a listener for the event) doesn't have to know/cares where the invoke came from; it just handles it and does its stuff.
Note however, that this also makes debugging a little bit harder since it is not that easy anymore to tell where the invoke came from ;)
Note: You can also add parameters to an Action
e.g.
public static event Action<int> SomeParameterEvent;
In this case ofcourse all methods have to also implement that parameter
public static InvokeSomeParameterEvent(int value)
{
if(SomeParameterAction == null) return;
SomeParameterEvent.Invoke(value);
}
In C
(the listener) you also have to receive the parameters
// name can be changed
private void OnSomeParameterEvent(int value)
{
//...
}
And ofcourse also call it with the parameter in B
MyEvents.InvokeSomeParameterEvent(someInt);
And than you can take it even on step further and instead of a value or a reference pass a complete delegate
method as parameter. See examples here