Game Design Pattern: Observer- Game Dev Series 139
Objective: quick introduction of Observer Game Design Pattern.
In this tutorial we are going to use Observer game design pattern to create a Player chasing function when we pressed space key. The concept of Observer game design pattern is creating a function with delegate that would be processed only if it was called under some condition.
The easiest way to understand this design pattern is achievement system. The achievement effect will not play if you have not finished the needed condition.
In this example, we would use a cube as target/player. When pressed space key, the chasers, which is capsules, would move approaching target position.
You would need to assign Nav Mesh Agent to each capsule, and also set the floor as static to bake the moveable area.
First, create a Target script and assign it to Target.
Open the script and set an event Action with type Vector3, which would be the data we will pass through method.
Then inside Update(), use if statement to detect pressing space key. After that, we would use
onChasing? to check whether any script is calling this Action delegate or not. If so, it would pass in the Vector3 data of Target.
In here we use a question mark to shorten this condition checking. This can also be written as:
Now we have created the someone-might-call action delegate. Let’s make those capsules move.
Create a script called Chaser and assign it to all the capsule Chaser.
Then create an OnEnable() and an OnDisable() methods.
Then we need to set a reference of Nav Mesh Agent component in OnEnable().
After this, we can call onChasing() as a new method. Inside this new method, set the moving destination as Vector3 of Target from its passing in data.
The last step is removing the method from Action in OnDisable().
Let’s test it in Play mode.
Benefit of Observer design pattern
The best part of using this design pattern is you can freely duplicate Chaser many times as you wish. If there is a script calling onChasing, it would be able to move toward Target by using it.
The same result can be made with many ways. You can also use array to complete this function. However, you would need to get the reference of new capsule if you duplicate another one.
Here is a quick example of using array instead of using Observer design pattern:
As conclusion, this is a design pattern like there is always a method/function ready to be called. If you complete some condition, you would be allowed to process it. Like an observer always waiting there!