Categories
Coding Tips Game Development Unity Tips

Unity C# Listeners

In a previous post I talked about Interfaces and how they could be used to ensure that another class had an implementation of its properties and methods. I also wrote a post recently going over Actions and how they can be used to invoke logic on different scripts with subscriptions. Well this takes the best of both to allow scripts to essentially listen for something to happen and then run logic from a method when called.

The basic setup for a listening is one script to manage the listen and its calls, this can be its own class or just in a manager class that makes sense for it. Then another as the interface that is used in for each listener, normally just having a method or two that provides any details needed.

Example

Interface

The interface is setup just like any other, I personally like to add the word Listener at the end of the interface name so I know what the interface is intended for.

public interface ISomethingListener
{
    void SomeMethod();
}

Manager

The manager can just be in anywhere really so long as it is in a Monobehaviour class. The example below has it in its own class, where the user could all it from elsewhere. The OnSomethingHappened method could also be static to save a reference if need be.

public class SomethingListenerManager : Monobehavior
{
    public void OnSomethingHappened()
    {
        // Finds all listeners in the scene to call the method on.
	var _listeners = FindObjectsOfType<ISomethingListener>();

	// Goes through each listener and runs the method.
	foreach (var _l in _listeners)
	    _l.SomeMethod();
    }
}

Usage

Once you have the system setup and have the manager class attached or called in your scene all you’ll need to do is implement the listeners themselves and what they do like so.

public class SomeClassThatDoesSomething : Monobehavior, ISomethingListener
{
    public void SomeMethod()
    {
	// Your Code Here!!!!
    }
}

As listeners use interfaces you can also pass in values with the method(s) to add additional context to the listener as needed. Hopefully with the example you get the idea of how these work. As for where to use them, that is up to you. If you know you are going to need a lot of things to happen from a lot of classes then a listener can be great. They are also really useful to making sure certain bits of code execute in the right order.

I hope this helps with you coding endeavours, of course, if you have an questions or queries feel free to ask them in the comments you contact me via the contact form.

Leave a Reply

Your email address will not be published.