boldai.com

 
 
 
 

EventsΒΆ

When certain things happens in Unity, an event will be fired to the concerned objects. All events available are listed in the “Events” folder in the palette. Lets look at a simple example:

../_images/bouncing-box-1.png

Above is a scene with a cube hanging in the air. The floor has a very high bounciness, so when the cube falls, it will bounce multiple times before it comes to rest. Now, I want sparks to be emitted each time it hits the floor. I will use the sparks from the Particles standard asset package.

When a collider hits another collider, an OnCollisionEnter event will be fired once. We can hook into this event to instantiate the particles:

The Sparks has been dragged in from the project view, and they will be instantiated at the current location with the identity rotation. After 0.75 seconds (the energy of the sparks), they will be removed from the hierarchy.

The Collision argument to the OnCollisionEnter event contains some information about the collision itself, such as the object we collided with as well as a contact point array.

Mouse events are nicely handled with events as well – the OnMouseDown/Up events will be fired when this object is clicked on. By using these, we can add a force to the box when it is clicked on:

And the end result can be seen while paused:

../_images/bouncing-box-4.png