1
\$\begingroup\$

I am building a 2D board game in Unity with a static camera pointed down at the game board. During the active phase of each player's turn, I want to detect where they click on the board. Fortunately, the board is laid out in an easy rectangular grid. (Essentially a trio of 5x5 grids).

Which of the following would be best practice to implement this?

  1. Create invisible colliders for every square on the board and create a translation function that translates those back to board positions (5,3) with Raytracing?

  2. Get the translated coordinates of the click and use a function to figure out which square (if any) the click is in using the mouseclick event handler (by calculating which square the grid coordinates fall in)?

  3. Make each square a button with its grid identity encoded and use that in its OnPressed function?

Edit: 4) Some other idea I haven't thought of yet?

Experience level: I'm just learning Unity, but have written a lot of C# (and tons of other code).

\$\endgroup\$
2
  • 1
    \$\begingroup\$ All of these methods will work. Which one do you most like working with? Beware of relying on strangers to identify what is "best" for you, because very often there is no such thing, or the judgement of "best" is contingent on details of your situation that you know much more deeply than we Internet randos do anyway. \$\endgroup\$
    – DMGregory
    Aug 2, 2020 at 16:05
  • \$\begingroup\$ I was hoping that there might be a consensus "usually handled like X" way, which is why I asked for the general "best practices". I'm new to working with Unity, and it disables a lot of the tools I usually use, so I thought I'd see if more experienced people knew of a standard method. \$\endgroup\$
    – JKreft
    Aug 2, 2020 at 18:39

1 Answer 1

3
\$\begingroup\$

As with every problem, there are many ways to come to a solution. But one solution I usually find the easiest to implement is:

  1. Add an EventSystem to your scene. Which happens automatically when you add a Canvas for your UI.
  2. Add a Physics Raycaster component to your camera (Physics Raycaster 2D if you want to use 2d colliders)
  3. Add an appropriately shaped Collider to every object you want to be clickable (a Collider2D if you've chosen the PhysicsRaycaster2D).
  4. Add a script to those objects which implements the interface IPointerClickHandler.

Now every mouse-click will call OnPointerClick(PointerEventData pointerEventData) on the object under the cursor. You just need to implement it.

\$\endgroup\$
1
  • \$\begingroup\$ Fantastic answer \$\endgroup\$
    – Natalo77
    Aug 4, 2020 at 16:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .