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.