Unibbl

Anime 3D SFX's Unity Tech Blog.
We created Antistar and Darwin's Nightmare

Unity 4.6: EventSystem and Raycaster

I was looking for a way to:

  • Find out which object in the 3D world is “under a mouse click”
  • Find the coordinates of a mouse hit in the 3D world.

Physics.Raycast can help you here. It is well documented too. But there’s a new system shipping with Unity 4.6 - and you probably want to use this instead.

The only problem with EventSystem is that, there are not many examples around and the manual isn’t very helpful (a video tutorial here, and a quick explanation at Unity Dojo).

So… Let’s take it step by step:

Hey, we can handle events when clicking on objects in a 3D scene

You want to implement one of the supported events, such as OnPointerClick.

[simple event handler source code]

Have a look at PointerEventData. This contains all the information you will ever need, including hit position in 3D world, click count, which button was pressed, and so forth.

Once you are done with this, you can use this script with any object, and the function will be called when you click on this object.

What, you don’t want to code?

If you don’t want to write you own handlers, you can use EventTrigger, which basically lets you invoke a function onto a target object in answer to any of the supported events.

The poison

If you run this “as is” it won’t work. This is because, by default there is no event system setup in your scene. In other words, everything is missing.

The remedy

  • Create an empty object and call it event system (or anything you like)
  • Add the EventSystem component.
  • In EventSystem Component select “add default input modules”. This will add support for touch input and standalone (aka desktop) input.
  • Add PhysicsRaycaster to your main camera.

You will now see debug output when clicking on any object using the sample script.