Techshop

Unity Tutorial 23 - Scoring Linking with Events

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;

[Serializable]
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…

The "On Spawn Coin".

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

"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.

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

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..

OnSpawnCoin.Invoke();

Save the code & run the game…

Doh!

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;
		UpdateText();
	}

	public void AddFunds() {
		funds += 10;
		UpdateText();
	}


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 TAG 019_AddingEvents

And we have a game…


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

Unity - A simple tutorial < Unity Tutorial 22 - Adding the GameController Unity Tutorial 24 - Refining the game part 1 >