In this lesson, you will create a MouseEvents
MonoBehaviour Script that will allow you to send messages between Game Objects when the mouse cursor interacts with them.
Start by creating a test scene where you will be able to test your MouseEvents
script in isolation. In this scene, you will create a small map 5x5 Grid. On the Grid you will have tiles that you the player can interact with (empty tiles) and tiles that the player cannot interact with (occupied tiles).
When you're finished you should have a Scene that looks similar to the picture below:
Unity provides several methods that can be used to detect mouse events that occur on Game Objects that have a Trigger Collider. To make use of this, you will write a script that detects Mouse Events that events.
MouseEvents
OnMouseEnter()
method to the scriptOnMouseEnter()
add a Debug.Log
message to help test the scriptDebug.Log
, specify this
as the context object. This will allow you to click on it in the console to see the attached Game Object.For a Game Object to receive mouse events, it must have a Trigger Collider attached. When the mouse cursor interacts with that Trigger Collider any MonoBehaviours that are attached to the same Game Object have their appropriate OnMouseXYZ
method invoked.
MouseEvents
component to the model
child componentBoxCollider
component to the model
child componentEdit Collider
icon to verify the shape of the collider matches your modelWhen you have finished, your Tile Prefab should look similar to the image below:
Test to ensure your MouseEvents
are being triggered
Next, you will add a UnityEvent so the parent Tile can listen to the mouse events and perform an action.
UnityEvent OnEnter
to your MouseEvents
scriptOnMouseEnter
method triggers, it should invoke the OnEnter
eventOne of the biggest benefits of a UnityEvent
is the ability to add functionality through the Inspector. To test that your event is firing properly, you can attach an action to it in the Inspector.
OnEnter
event in the Inspector+
icon to add an event listenerTile
parent object to the new listener
SetActive
function. If all went well, the Tiles should deactivate in the Hierarchy. This is because you have registered Tile.SetActive(false)
to be invoked when the OnEnter
event is triggered.
SetActive
event from the event listTile
's name in the Hierarchy to "MouseEntered"When you have finished, your scene should act similar to the video below:
OnExit
UnityEvent to your MouseEvents
scriptOnClick
UnityEvent to your MouseEvents
scriptOnMouseExit
to Invoke
OnExit
OnMouseUpAsButton
to Invoke
OnClick
When you have finished this challenge, your Test Scene should act similar to the video below:
With a MouseEvents
implemented and ready to use, you can now create a TileCursor that will track which tile the player will interact with when the press the mouse button.