Add a distractive game object in Unity

Samarth Dhroov
4 min readOct 21, 2021

The exercise here demonstrates adding a game object to distract enemy from its designated track of movement.

Below is the basic sequence of this entire act.

  1. The player should be given a clue as soon as he reaches a certain area from where the only way out is to get the guards to a different location.
  2. In order to do so, the player should have a mechanism to initiate a distraction.
  3. The set of guards must respond to the distraction.

Here is how each of them could be addressed.

  • The trigger game object
Unity

This is a 3d object with mesh renderer unticked in place.

It needs a modular script so that going forward, it could be used for other such trigger objects as well.

C#
Unity

This is going to trigger the audioclip as soon as the player touches the object and the clue would be audible.

  • Distraction mechanism

If the player presses right mouse button, a coin object gets instantiated at the location of click.

So, in the update method of the player script, the following code shall work.

C#
Unity
C#

To make sure that it only happens once, a bool flag would come handy.

C#
C#

As soon as, the first click is recorded, the coin object would be instantiated and the flag would change its value. Once the flag shifts, this action remains unavailable.

  • Distraction Response

Since the project is using navmesh for movement of all objects, it seems reasonable to use it again.

The key is here is that the player object has a script which triggers distraction and the set of guards responds to this act. Therefore, multiple interaction are inevitable between these objects which is going to result into multiple references.

C#
C#
C#

The method here is part of the player script but it gets references to the navmeshagent components of all security guards and sends them to the position of mouse input.

Although everything seems in place, the result would be Null because the guard has a script containing update method with some code. In order for them to respond to this distraction, the player script has to communicate with it and it could be done by a bool flag.

So below is some controlling code for the guard script.

C#
C#
C#

And, here is some controlling code for the player script.

C#

The animation for each act has been pre-recorded for all objects and the basic implementation is done using bool and trigger.

Unity

That should be it :)

Thank you very much

--

--