Game Development Reference
In-Depth Information
MonoBehaviour events
To close this chapter, let's consider some of the events Unity offers us already for
working with event-driven programming. The
MonoBehaviour
class already exposes
a wide range of events that are called automatically under specific conditions. These
functions or events begin with the prefix
On
and include events such as
OnGUI
,
OnMouseEnter
,
OnMouseDown
,
OnParticleCollision
, and others. This section
considers some details for common event types.
The full list of
MonoBehaviour
events can be found in the
Unity documentation at
http://docs.unity3d.com/
Mouse and tap events
One set of useful events is the mouse-input and touch-input set of events. These
include
OnMouseDown
,
OnMouseEnter
, and
OnMouseExit
. In the earlier versions of
Unity, these events were only triggered for mouse-specific events and not touch
input. But more recently, touch input has been mapped to them; meaning that a
tap will now register by default as a mouse event. To clarify,
OnMouseDown
is called
once when a mouse button is pressed down while the cursor is hovering on an
object. The event is not, however, called repeatedly until the button is released.
Likewise,
OnMouseEnter
is called once when a cursor first hovers over an object
without having exited and
OnMouseExit
is called when the cursor hovers away
from an object it has previously entered. The success of these events depends on
an object having a collider component attached to approximate its volume within
which mouse events are detected. This means that none of the mouse events will fire
without a collider attached to the object.
However, there are occasions when
MouseEvents
will not fire, even with a collider
attached, because other objects (with colliders) are obscuring the objects you need
to click on based on the current view from the active camera. That is, the clickable
objects are in the background. You can, of course, solve the issue (at least in many
cases) by simply assigning the foreground objects to an
IgnoreRaycast
layer
making them immune from physics raycast operations.