Click strategy

Hello,

I work with Unity for a long time now, and I there is still a concept that bothers me: the click strategy.

What strategy do you use when it comes about player interactions?

  • When player clicks on the scene do you have a high entity that will receive the input, do the raycast to check on what part of the screen the player has clicked, and throw the click information to a lower component according to the clicked object ?
  • When player clicks on the scene do you make all your “clickable” entities check if the click was for them (that means a raycast per clickable entity) ?
  • When player clicks on the scene do you use magic?
  • When player clicks on the scene do you treat UI and interactive game object differently? How?

My problem is either to have to many raycast made or not being fully able to handle specific situations like non-interactive objects when the game is supposed to be paused…

I can’t find any documentation about what strategy is the best so I wonder how you do that kind of click management logic.
Thanks for your help.

Here’s a simplified version of the current method I’m using for my game (which is a 2D point and click game written in javascript):

Click Script + Input Manager

I have an empty game object with 2 scripts attached, ClickScript and InputManager.

Click script basically sends a raycast out from the main camera and when it hits a box collider it sends the raycast info to the input manager like this:

if (Input.GetMouseButton(0))
{
  // A function that does one raycast and returns a raycast hit.
  raycastHit = GetRaycast(); 

  // Call the function OnLeftClick on the inputManager and send the raycastHit as a parameter
  inputManager.OnLeftClick(raycastHit);
}

And in the InputManager:

function OnLeftClick(raycastHit : RaycastHit2D)
{
  // If you've clicked a person...
  if (raycastHit.collider.CompareTag("Person"))
    {
      TalkToPerson();
    }
  // If you've clicked an exit...
  else if (raycastHit.collider.CompareTag("Exit"))
    {
      Exit();
    }
}

And so the tag of the game object you click on determines what happens. It took me ages to work out this method and I’ve found that it is very flexible and very quick to work with and to add new features into the game.

If its a 2D game youre making I can direct you to a couple of handy sites/ scripts for Unity.

I’ve had success doing it this way:

Tag each object that you want as clickable with a “clickableObject” tag in the inspector.

Code:

Ray clickRay;
float distance; //need to put in some value depending on what you need

...
...


//the following would usually go in Update()

clickRay = mainCamera.ScreenPointToRay(Input.mousePosition);

if (Input.GetAxis("Fire")
{
 if (Physics.Raycast(clickRay.origin, out objHit, clickRay.direction * distance))
   {
     if (objHit.collider.tag == "clickableObject")
      {
        //do something that you can only do on a clickable object
      }
   }
 }