0
\$\begingroup\$

I'm making a simple puzzle game.

I can very easily detect if a player touches my GameObjects, by turning on colliders and using OnMouseDown.

In my game, when a player touches a GameObject... that GameObject starts a particular action.

The most intuitive way for a player to stop that action is to just touch anywhere on the screen other than that particular GameObject (like say, the empty screen). That way the game will know that the GameObject has no longer been selected.

How can I detect if someone has touched an empty screen?

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Why not have the same logic on your empty scene? Just because it looks enpty for the user does not mean you can't just put there an object that still reacts to your clicks \$\endgroup\$
    – Zibelas
    May 22, 2022 at 11:54
  • \$\begingroup\$ @Zibelas you are a genius!! Thank you! \$\endgroup\$
    – kanamekun
    May 23, 2022 at 3:08
  • \$\begingroup\$ @Zibelas - would you mind adding this as an Answer, so that I can accept it? Thank you!! \$\endgroup\$
    – kanamekun
    May 26, 2022 at 11:55

2 Answers 2

2
\$\begingroup\$

The quick way for rapid prototyping would be to simply have an object that can react on clicks as well on your background. Just because the user thinks the background is empty does not mean you can't have an object there that reacts on clicks.

This could of course cause some other problems as well if it ever gets rendered on top of all your other objects. But for a start it is good enough to get it running and focus on the other parts.

\$\endgroup\$
0
\$\begingroup\$

Just set a boolean clickedMe in OnMouseDown if this object was the one clicked on. If you get to Update and Input.GetMouseButtonDown(0) says there was a pointer click this frame, but clickedMe is false, then that click must have been on another object or no object at all.

bool clickedMe;
bool amSelected;

void OnMouseDown() {
    clickedMe = true;
    amSelected = true;
}

void Update() {
    if (Input.GetMouseButtonDown(0)) {
        if (clickedMe) {
            // Reset to false to use in future frames.
            clickedMe = false;
        } else {
            // Clicked elsewhere - deselect me.
            amSelected = false;
        }
    }
}

A more robust and efficient solution is to make your own pointer interaction script with just a single instance in the scene. When the mouse is clicked, fire a ray to see what it hit. You can then store that object as the last touched target, and let it know that it's been deselected if a later click ray hits nothing / another object. This way you have just one script polling input every frame, not multiple, and you can centralize management of selected objects, different selection modes, etc.

\$\endgroup\$

You must log in to answer this question.

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