Implementing the Publish–subscribe pattern in Unity

Implementing the Publish–subscribe pattern in Unity

The publish-subscribe pattern is a messaging pattern. It consists of a message publisher which publishes a message. There exist subscribers to the publishers that listen to the messages published by the publishers.

Publish–subscribe pattern flowchart

There are scenarios when we use the publish-subscribe pattern. For example, consider a scenario where all enemies are destroyed on picking up a powerup. This is a very common usage scenario of the publish-subscribe pattern in Unity.

In this article, we will create a simple publish-subscribe pattern in unity using the C# language.

Creating the Publisher

We will use the concept of events & delegates in C# to create a publisher.

I recommend you to go through events & delegates, if you don’t know these concepts

To create a publisher, we start with creating a class named Publisher.cs and get rid of the Start() and Update() method.

Now declare the following delegate & event.

public delegate void PublishEvent ();
public static event PublishEvent Publish;

The first statement defines the signature of the delegate that will be used to publish the event.

The second statement declared a static event variable that others can subscribe to.

Now define a method named PublishTheEvent(). This method will Publish the event when required and the subscribers will listen to this published event.

public void PublishTheEvent ()
{
	if (Publish != null)
		Publish ();
}

Now the final C# file will look like:

Publisher.cs

using UnityEngine;

public class Publisher : MonoBehaviour
{
	public delegate void PublishEvent ();
	public static event PublishEvent Publish;

	public void PublishTheEvent ()
	{
		if (Publish != null)
			Publish ();
	}
}

Creating the Subscriber

To create a subscriber, we will start similarly by creating a new C# file named Subscriber.cs and get rid of the Start() and Update() methods.

Now, define the built-in Unity hooks OnEnable() and OnDisable() which are called whenever the gameobject is enabled or disabled.

Now create another method named Destroy()

The signature of the destroy method must match with the signature of the delegate declared in the Publisher.cs

void Destroy ()
{
	Destroy (transform);
}

At this point, the Subscriber.cs will look like:

using UnityEngine;

public class Subscriber : MonoBehaviour
{
	void OnEnable ()
	{
	}

	void OnDisable ()
	{
	}

	void Destroy ()
	{
		Destroy (transform);
	}
}

Now, we need to subscribe to the Publisher events. This can be done by appending the method call to the delegate using the += operator.

Modify the OnEnable() and OnDisable() methods to look like:

void OnEnable ()
{
	Publisher.Publish += Destroy;
}
void OnDisable ()
{
	Publisher.Publish -= Destroy;
}

Now the final Subscriber.cs will look like:

using UnityEngine;

public class Subscriber : MonoBehaviour
{
	void OnEnable ()
	{
		Publisher.Publish += Destroy;
	}

	void OnDisable ()
	{
		Publisher.Publish -= Destroy;
	}

	void Destroy ()
	{
		Destroy (transform.gameObject);
	}
}

Using the Publish-Subscribe Pattern

Using the publisher & subscriber we created is simple.

We will attach the publisher script to the PowerUp gameobject or the gameobject that will be broadcasting the message/event.

Since, we are currently not having any PowerUp gameobject, we will simple attach the Publisher.cs script to an empty gameobject.

 

attaching the publisher script to an empty gameobject
Attaching the publisher script to an empty gameobject

Now attach the Subscriber.cs script to the enemies. Here also, I am attaching the script to some empty gameobjects as we actually don’t have an enemy.

attaching subscriber script to empty gameobjects
Attaching the subscriber script to enemies

Now, in order to actually see the Publish-Subscribe pattern in action, we need to trigger the PublishTheEvent() method in the Publisher.cs. To do this, I am using a mouse click on the game view.

Create a new script named InputAction.cs and attach it to the Publisher gameobject.

Modify the InputAction.cs to the following content:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InputAction : MonoBehaviour
{
	void Update ()
	{
		if (Input.GetMouseButtonDown (0)) 
		{
			transform.GetComponent<Publisher> ().PublishTheEvent ();
		}
	}
}

Now run the game & just click anywhere on the game view. As soon as you click on the game view, the Enemies will be destroyed immediately.

destroying the enemies using the publish-subscribe pattern
Destroying the enemies using the publish-subscribe pattern

The enemies had a subscription to the event broadcasted by the Publisher. Hence, clicking the game view broadcasted the event and the subscriptions, after listening to the broadcasted event, gets destroyed immediately as described in the Subscriber.cs file.

This is the Publish-Subscribe pattern in Unity.


One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.