Part 23 - Scoring links with events.

By Jamie Chatterton / 2018-06-12

We have the GameController ready to do things.

However, nothing is telling it what to do.

We need to inform it when things happen. What are these things? Events

Unity has the notion of events in it. It has a base class of UnityEvent.

These events are C# delegates. In that you can attach multiple functions to them and invoke them all with optional parameters. However, unlike delegates in code, we can use the front-end to visually attach them.

In your C# editor, in the scripts folder, create a class called CoinEvent.

When it's finished it wants to look like

using System;
using UnityEngine.Events;

public class CoinEvent : UnityEvent {

It needs to be marked as Serializable so that it can be attached to other objects and edited as an attribute in the ide.

Go to the SpawnerController. Add a new public attribute, OnSpawnCoin of type CoinEvent and assign a new instance of it, as so…

public CoinEvent OnSpawnCoin = new CoinEvent();

Make sure everything is saved and go to the Unity IDE. There should be a new editable field for the Spawner Controller Component, in the spawner object…

Open this image in a new tabNew OnCoinSpawn field
New OnCoinSpawn field

The "On Spawn Coin".

Click on it's "+", it'll change to

Open this image in a new tabOnCoinSpawn field details
OnCoinSpawn field details

"Runtime Only" means it'll only be executed when the game runs.

Drag the GameController from the Hierarchy onto the "None (Object)" box, so we can give it an object from which we can select a function to invoke.

Open this image in a new tabList of callable things
List of callable things

The menu under the "No Function" gives us a list of all the components and the functions we can call.

Open this image in a new tabSpendFunds can be found here
SpendFunds can be found here

And in there is the SpendFunds function we added before. So select that.

We still haven't told it to call it yet.

In SpawnObject of the SpawnerController. At the end of the function add the call to the OnSpawnCoin method..


Save the code & run the game…


Check the GameController as the game is running. The Funds should be going down. But the funds aren't updating…

Forgot one thing… Update the funds

In the GameController. In both SpendFunds and AddFunds, after the funds are changed, add a call to UpdateText

public void SpendFunds() {
	funds -= 10;

public void AddFunds() {
	funds += 10;

So now it's costing money… How about getting it back?....

Kinda the same, but in the DeleteCollidingObjects class.

Add a public attribute, of type CoinEvent.

Invoke the CoinEvent instance in the OnCollisionEnter method after destroying an object.

In the IDE bind it to the GameController.AddFunds method

I won't go into the specifics but the final code and changes to the scene are in the commit.

Git repository:

And we have a game…

It has problems. But we have a basic outline of a game.

More posts in this series.