Computer Programming

Listener

Observer Pattern in Unity

Observer pattern in Unity

Today I’m going to cover how to quickly and easily understand and implement the observer pattern in Unity. This pattern has a few alternative names including event-listener and publisher-subscriber.

First, why should this technique be used? Without getting too deep the answer is clean code and SOLID principles. In short, these techniques make your code easier to understand, scalable, reusable, maintainable, and so forth.

The publisher-subscriber pattern is lengthy when described in words, but quite simple when demonstrated with examples in Unity. I would consider it an essential programming pattern to know and memorize. The easiest way to understand and learn the pattern is by looking at the problem it solves.

Observer pattern example

Consider the following example where you have two scripts:

Script #1 (Resource Manager): The Resource Manager script tracks money and gets called whenever money is added or subtracted. Again, it is the source of truth with regard to how much money the player has at any given moment.

Script #2 (UI): The UI script should show on the screen how much money the player has at any given moment.

The Resource Manager script is simple enough. It would have a private variable representing the amount of money available and it would likely have a few public methods to add or subtract money.

So what’s the problem? Well, the UI script needs to update the amount of money available on the screen and the amount of money does not change very often. We also want to avoid tightly coupled code; scripts that reference each other.

Dissecting the example

The first “wrong” approach would be for the Resource Manager script to have a reference to the UI script and to directly call a method in the UI script whenever the amount of money changes. The Resource Manager script should not need to know anything about how the UI scripts works internally; this also gets out of control once additional scripts for things like players, enemies, and additional resources are added.

The second “wrong” approach is for the UI script to constantly call a method in the Resource Manager script every frame in the Update method. This is an improvement, but it’s hugely wasteful because the quantity of money available doesn’t change very often; certainly not 60 to 100 times per second. You can imagine how performance might be impacted by this sort of approach.

The solution is the observer pattern. The UI script should have a reference to the Resource Manager script. The Resource Manager script knows when the amount of money changes; it has methods specifically to add and subtract money, remember? The Resource Manager should notify any other script that wants to know about changes to money. Finally, the Resource Manager script should not need to know anything about the scripts that want information about changes to money from it.

Let’s look at how to achieve this desired outcome. This is outlined below.

  • Resource Manager script
    1. Declare a public event handler
    2. Raise the event when the amount of money changes
  • UI script
    1. Get a reference to the Resource Manager script
    2. Subscribe to the event
    3. Fire a method when the event is raised
Pseudo code examples

Events may or may not pass data to the listener. Raising an event without passing any data is simpler. We’ll look at both techniques starting with the simpler version. Let’s start with some extremely reduced pseudo code just to outline the concept.

Example 1: Raising events without sending data.

Publisher script (Resource Manager)

// required for events
using System;
// declare the event (EventHandler is a delegate)
public event EventHandler OnMoneyChange;
// raise the event and notify any subscribers
OnMoneyChange?.Invoke( this, EventArgs.empty );

Subscriber script (UI)

// required for events
using System;
// subscribe to the publisher by providing a callback method
Broadcaster.OnMoneyChange += MethodToFireInListener;
// define the callback method to fire when the event is raised
private void MethodToFireInListener( object sender, System.EventArgs e )
{
	// do something
}

Example 2: Raising events that pass data.

Publisher script (Resource Manager)

// required for events
using System;
// declare the event and provide a custom data type
public event EventHandler<OnMoneyChangeEventArgs> OnEnemyDeath;
// define the custom data type to pass via the event
public class OnMoneyChangeEventArgs : EventArgs
{
	// define anything you want to pass
	public int someInt;
}

// raise the event and notify any subscribers
// populate the data to pass to the subscribers
OnMoneyChange?.Invoke( this, new OnMoneyChangeEventArgs { someInt = 1234; } );

Subscriber script (UI)

// required for events
using System;
// subscribe to the publisher by providing a callback method
Broadcaster.OnMoneyChange += MethodToFireInListener;
// define the callback method to fire when the event is raised
private void MethodToFireInListener( object sender, Broadcaster.OnMoneyChangeEventArgs e )
{
	// do something with the data
	Debug.Log( “someInt: ” e.someInt );
}
How events work

EventHandler is a ready-made delegate defined in the system namespace. Delegates are a collection of call-back methods. You can define your own, but it adds another layer of complexity and the pre-made one works fine for most use cases. Subscribers or listeners can add and remove call-back methods to the delegate. When the event is raised by the publisher and the delegate is executed all of the call-back methods the delegate references get fired.

As a general disclaimer, what I’m teaching here is not the only way, the best way, the most efficient way, or the definitive 200 IQ PhD level solution; it’s a simple, high level, easy-to-understand explanation to get you quickly solving real world problems. Please see the suggested reading list below for a deeper dive. I teach this way because information overload is a huge problem when it comes to learning computer programming.

Just for completeness I am providing some more complete examples in the off chance the abbreviated examples above are not clear. This could prove helpful for some learners.

Complete Unity code example

Raising events without sending data.

Publisher script (attached to a 3d cube object)

using UnityEngine;
using System;
public class Publisher : MonoBehaviour
{
    public static Publisher Instance { get; private set; }
    public event EventHandler OnSpacebarDown;
    private bool isSmall;
    private void Awake()
    {
        Instance = this;
    }
    private void Update()
    {
        if ( Input.GetKeyDown( KeyCode.Space ) )
        {
            isSmall = !isSmall;
            if ( isSmall )
                transform.localScale = new Vector3( 0.5f, 0.5f, 0.5f );
            else
                transform.localScale = new Vector3( 1.0f, 1.0f, 1.0f );
            OnSpacebarDown?.Invoke( this, EventArgs.Empty );
        }
    }
}

Subscriber script (attached to a different 3d cube object)

using UnityEngine;
using System;
public class Subscriber1 : MonoBehaviour
{
    private bool isRotating = false;
    private void Start()
    {
        Publisher.Instance.OnSpacebarDown += Publisher_OnSpacebarDown;
    }
    private void Publisher_OnSpacebarDown( object sender, EventArgs e )
    {
        isRotating = !isRotating;
    }
    private void Update()
    {
        if ( isRotating )
        {
            transform.Rotate( new Vector3( 25.0f, 0.0f, 0.0f ) * Time.deltaTime );
        }
    }
}
William M Coyne, PharmD, MBA

Start Your Video Game Career: Proven Advice on Jobs, Education, Interviews, and More for Starting and Succeeding in the Video Game...

William M Coyne, PharmD, MBA

This is considered a beginner-intermediate book, but some previous programming experience is required. The author does spend some time...

William M Coyne, PharmD, MBA

Agile Principles, Patterns, and Practices in C# is a book written for professional software developers working for large corporations...

William M Coyne, PharmD, MBA

It is possible to create your own custom packages should you wish to share your assets or tools with other developers or sell them on the Unity Asset Store...

Learn C# in One Day and Learn It Well

Learn C# in One Day and Learn It Well Review

Learn C# in One Day and Learn It Well
Brief synopsis of Learn C# in One Day and Learn It Well

Learn C# in One Day and Learn It Well is a short introduction to the C# programming language. It’s focused on syntax and not so much answering how or why things work. It’s succinct and does an adequate job covering the most common features required to get you started. It will not teach you the language well in one day. It’s inexpensive and serves as a quick shot of dopamine; you’ll finish it fast, learn something, and feel a sense of accomplishment. Unfortunately, if you don’t immediately quit programming right after reading this thing you’re going to need another book to expand your knowledge. There is, however, something to be said about repetition and incremental achievement milestones. For the price it’s worth a look.

Length

This book is 148 pages in length not counting the appendix and index at the end.

Target audience

The target audience for this book is beginners with limited programming experience. I say limited because I want to highlight that this book may not be appropriate for someone with zero programming experience. Why? Because the author does not explain very basic low level assumptions related to code execution, what IDEs are, what .NET is, etc. This could leave someone with zero programming experience with a lot of unanswered questions. If you’re coming from another programming language this book will get you started quickly, but it will not cover advanced features or techniques you’re certain to want to know.

Relevance to game development

The relevance of this book to game development using Unity 3D is high. However, it won’t teach you anything about Unity-specific functionality. Still, it’s a powerful start and it’s just so easy to finish. If you’re at all intimidated by scripting in Unity (and dense textbooks for that matter) this book will provide a quick confidence boost.

How Learn C# in One Day and Learn It Well should be read

The book should be read from start to finish. However, the index at the back of the book means it can also be used as a quick reference for basic syntax questions when you forget how to implement a language feature.

Best features

The author does a great job limiting his scope. Things are greatly simplified and leaned out. As a result you’ll cover a lot of ground in a very short period of time. You’ll never get bogged down in complex explanations because there aren’t any. It’s a functional book focused on syntax. Syntax is just a piece of the puzzle, but it’s a substantial piece and, well, you’re technically programming once you have it down.

What I wish was different

There is nothing substantial I would change about this book. This is because it’s lean and the scope is limited. Anything I can suggest would end up changing the scope. For example, adding more content to cover the complex aspects of C# programming or explaining how and why things work. All of this combined with a low price means there is really nothing to complain about. There is really no way the reader’s expectations will not be met. I think this explains the very high rating on Amazon, but it could also be related to reader ignorance. After all, they don’t know what they don’t know.

Writing quality

The book is well written with very few typos or errors. The author assumes a completely neutral tone. I don’t detect any personality and there are no opinions or advice of any kind. The only thing I detect is spelling variations that suggest the author is British.

Code quality in Learn C# in One Day and Learn It Well

The code examples are very brief and pragmatic. In fact, the author keeps the code examples throughout the book extremely short. This is in contrast to the average author of a computer book. Instead, this author creates one large code example at the back of the book that demonstrates all of the concepts taught throughout the book. This really helps keep the page count down, but might not mesh well with some readers. I could also see this as being overwhelming.

Author’s attitude

As mentioned above, the author does not convey much of a personality. This is fine, of course. I have nothing negative to say about his writing. It’s merely an objective observation.

Should you buy Learn C# in One Day and Learn It Well?

I would recommend this book to someone hesitant to start programming in the C# language. However, if you’re not somewhat familiar with what programming is and how it works I would recommend supplementing this text with something else. If bigger textbooks don’t scare you and you’re hungry for knowledge you can safely skip this one for a more comprehensive selection like Illustrated C# 7 for example. For me this book was nothing more than a self-esteem boost. I felt good plowing through it quickly because the content was so easy to understand. However, the feeling wore off quickly once I realized I hadn’t really learned that much.

William M Coyne, PharmD, MBA

Start Your Video Game Career: Proven Advice on Jobs, Education, Interviews, and More for Starting and Succeeding in the Video Game...

William M Coyne, PharmD, MBA

Agile Principles, Patterns, and Practices in C# is a book written for professional software developers working for large corporations...

William M Coyne, PharmD, MBA

Today I’m going to cover how to quickly and easily understand and implement the observer pattern in Unity. This pattern has a few alternative...

William M Coyne, PharmD, MBA

It is possible to create your own custom packages should you wish to share your assets or tools with other developers or sell them on the Unity Asset Store...

Illustrated C# 7

Illustrated C# 7 Review

Brief synopsis of Illustrated C# 7

First and foremost, I will be approaching this Illustrated C# 7 review from a Unity 3D game developer’s perspective. This is considered a beginner-intermediate book, but some previous programming experience is required. The author does spend some time explaining the .NET framework, but no pages are specifically dedicated to orienting a brand new programmer with zero experience. Someone with absolutely no idea where to start would struggle with this book as a result. As such this is a better second book than it is a first book.

The author makes numerous references to the C++ language in passing. Almost as if he expects many readers to have some experience with that language already. It is not at all necessary to understand these C++ language references, but it is interesting they are included in the text.

The book does a great job taking the reader from a beginner to intermediate skill level. A great deal of effort is invested in explaining why things are the way they are in C# and how they work behind the scenes. This is not just a book about syntax and rules. The author will almost always take the time to answer your questions about how something works, why it works that way, and any lingering “what about this scenario?” questions you might have. I admire the ability of the author to almost telepathically predict my follow-up questions in this regard.

Length

This book is 783 pages in length not including the index.

Target audience

The book states the intended skill level is beginner-intermediate. The content is generic C#. No specific platforms (like Windows) are presented beyond a few brief examples which probably just serve to promote the author’s other book focused on Windows C# and WPF. The author does not over-promote his other work; it’s very modest and done well. Some previous basic programming experience is required.

Relevance to game development

Remember, this is an Illustrated C# 7 review from a game dev’s perspective. The relevance of this book to Unity 3D game programmers is high. This is because the C# being taught is platform-agnostic. However, because the book is a complete language reference it covers all of the object-oriented programming (OOP) abstractions C# has to offer. Some of the OOP abstractions are probably not immediately useful to a Unity 3D programmer. And, what’s more, if you haven’t read at least a single book on programming patterns you’re going to struggle to think of ways in which all of these abstractions might be useful.

How Illustrated C# 7 should be read

This book should be read linearly from start to finish and kept as a reference. I would not spend too much time trying to memorize all of the OOP abstractions. Since, again, this a complete C# language reference and not all of C# will immediately become useful to you, the reader. Instead, just be aware those tools exist and refer back to them as needed. Focus on higher level concepts and the kinds of problems that could be solved with a given bit of C# functionality. Your goal should be to understand what the tools are in your toolbox and generally what they are used for.

Best features

The best features found in this book are the diagrams, code examples, and code explanations. The diagrams are a boon for visual learners; the author uses them to convey complex concepts and they are highly effective at achieving this purpose. The code examples are clear and useful. The code examples are explained in a succinct bullet-point style which is tremendously helpful for learners.

What I wish was different

Where this book falls a little flat is its coverage of programming patterns (even extremely basic ones) or at the very least some greater depth in regard to the applicability of the different C# features being introduced. That is, more discussion about the kinds of problems the OOP abstractions can solve or interesting ways in which they might be combined. There is some discussion, mind you, just not enough in my opinion. However, in the author’s defense the book is already nearly 800 pages in length as it currently stands. One could easily argue this is simply beyond the scope of the book.

Writing quality

The writing quality is high. Only a few typos were identified; much fewer than average. The author slips in a few humorous lines here and there, but they are few and far between. The writing does not convey much in terms of personality, but it reads well.

Code quality in Illustrated C# 7

The example code segments are done quite well. They serve as clear and purposeful aids to written explanations. The code examples are also clearly explained in a bullet-point style format. I did not feel it was necessary to type anything into Microsoft Visual Studio myself.

Author’s attitude

As noted previously the writing does not convey a strong personality or much of the author’s own opinions. It feels more “factual” and objective. But, when the occasional opinion does show up I get the impression the author is humble and not at all arrogant.

Should you buy Illustrated C# 7?

The conclusion of this Illustrated C# 7 review is that this is an essential book; it bridges the C# beginner and intermediate levels. It also serves as a very useful reference and the diagrams are a rare treat for visual learners. It should be emphasized this is not a great first book, but it is an excellent second or third one. It is a rather large book and assumes the reader generally understands what programming is and to some extent how and where to create programs.

William M Coyne, PharmD, MBA

Agile Principles, Patterns, and Practices in C# is a book written for professional software developers working for large corporations...

William M Coyne, PharmD, MBA

It is possible to create your own custom packages should you wish to share your assets or tools with other developers or sell them on the Unity Asset Store...

William M Coyne, PharmD, MBA

Today I’m going to cover how to quickly and easily understand and implement the observer pattern in Unity. This pattern has a few alternative...

William M Coyne, PharmD, MBA

Start Your Video Game Career: Proven Advice on Jobs, Education, Interviews, and More for Starting and Succeeding in the Video Game...

Agile Principles, Patterns, and Practices in C#

Agile Principles, Patterns, and Practices in C# Review

Brief synopsis of Agile Principles, Patterns, and Practices in C#

Agile Principles, Patterns, and Practices in C# is a book written for professional software developers working for large corporations that make banking software (coincidentally this is precisely the type of company the author’s consulting firm primarily serves). The scope of this text is quite broad. It covers object oriented design, UML diagrams, test-driven development, programming patterns, and much more. However, it does so with verbose explanations and overly complicated code examples. At its core this book is teaching some important concepts, but it does so in such an unnecessarily convoluted manner that I have to wonder if it was intentional. That is, so the author is ultimately hired by a large corporation as a consultant speaker to clear up all the confusion he created himself. Don’t get me wrong, there are some diamonds buried in this text. The only problem is that only the most clever and dedicated readers will have the tools (and the patience) to uncover them.

Length

This book is 670 pages in length not counting the appendices and index at the end.

Target audience

The target audience for this book is clearly a professional computer programmer working in a formal corporate environment. As mentioned below, the first 12 chapters have the highest value for game developers.

Relevance to game development

The relevance of this book to game programming is moderate. There are some good general programming techniques scattered throughout the book. However, this text could be so much more applicable. The author blows it by including so much extraneous information, using bloated overly complex examples, and covering UML diagramming techniques he himself admits are a waste of time. Seriously, he literally introduces many of these topics as a waste of time and then concludes in the respective section summary they are a waste of time. Let that sit with you for a moment.

How Agile Principles, Patterns, and Practices in C# should be read

If you’re going to tackle this book I recommend reading the UML diagramming chapters first (in the middle), the programming pattern chapters second (at the end), and then going back to the start to finish the rest. The author starts the book off by using UML diagrams and programming patterns he doesn’t explain until much later in the text. The original order the information is presented in makes no sense. You could, alternatively, ignore the UML diagrams and programming patterns and instead just read the first 12 chapters (174 pages) to get the best bang for your buck.

Best features

The funny pictures and jokes scattered throughout the book are the best feature. The author’s overall writing style is pretty good as well, but can at times come off as overly clever and even arrogant if you’re not fond of sarcasm and wit. Overall I think the first 12 chapters (174 pages) are the best. If I had to choose a single chapter as being the best it would have to be chapter 6 (A Programming Episode) in which the author and a colleague walk through the development of a program designed to calculate bowling scores. It’s presented in an iterative test-driven design fashion while the two have a conversation back and forth. This chapter did a great job demonstrating how the developers think about solving problems.

What I wish was different

This is a 700 page book that should have been a 300 page book. Seriously, this would be explosively good if all of the fluff and extraneous complexity were distilled off. I would love to see a summarized version of this text covering the core concepts with very succinct code examples with no unnecessary algorithms or math puzzles.

Writing quality

There are many typos and errors in this book. I say many because this is a translation of the original title Agile Software Development, Principles, Patterns, and Practices. I would have expected a lot of the more obvious typos to have been caught during the conversion process. The author is, however, a genuinely good writer.

Code quality in Agile Principles, Patterns, and Practices in C#

The code examples in the book are bad for several reasons. First, there is simply way too much code in this book. It’s unnecessary. Second, the examples used are overly complicated. The author is obsessed with making everything a puzzle; nothing is straightforward. When a simple concept is being demonstrated the author will always, and I mean always, insert some kind of math problem or algorithm to make things more complicated. Third, this book was converted from another language (C++ and Java presumably) but it does not utilize advanced C# language features. The conversion was pretty basic. Don’t expect to learn anything special about the C# language itself.

Author’s attitude

The author has a crass and sarcastic sense of humor. I can appreciate this, but based on some of the negative reviews on Amazon people tend to interpret this as arrogance. I will concede with the negative reviewers on Amazon that the author does attempt to be excessively clever/witty in his writing by inserting obscure literary references all over the place. In short, the jokes are good but he goes overboard with the cleverness at times. Yes, we get it, you read lots of books.

Should you buy Agile Principles, Patterns, and Practices in C#?

I would not buy this book new, but if you can find it for a low price on the used market I would read the first 12 chapters. The rest of it can safely be skipped. Doubly so if you’re a game developer. That, or just read the introductions and summaries of the later chapters. I don’t regret my purchase and I did learn a lot. It just came across like the UI and crafting system in Animal Crossing: New Horizations: sadistic by design.

William M Coyne, PharmD, MBA

It is possible to create your own custom packages should you wish to share your assets or tools with other developers or sell them on the Unity Asset Store...

William M Coyne, PharmD, MBA

Agile Principles, Patterns, and Practices in C# is a book written for professional software developers working for large corporations...

William M Coyne, PharmD, MBA

This is considered a beginner-intermediate book, but some previous programming experience is required. The author does spend some time...

William M Coyne, PharmD, MBA

Learn C# in One Day and Learn It Well is a short introduction to the C# programming language. It’s focused on syntax and not so much...