Question about buttons press on Gameobjects

I’m trying to make Two game objects with different reaction if I Clicked on each one of them…
but the result I get is: Both of the game objects get clicked even when I click Away from both of them.

here is my scripts:

public class FirstClass : MonoBehaviour {


	void Update () {
		if (Input.GetKeyDown(KeyCode.Mouse0))
			Debug.Log ("GameObject1 has been clicked");
	}
}

second script :

public class SecondClass : MonoBehaviour {



	void Update () {
		if (Input.GetKeyDown (KeyCode.Mouse0))
			Debug.Log ("Gameobject2 has been clicked");
	}
}

is there special code for this ? like making it as button or something?

If you want to click on an in-scene game object that isnt in a Canvas (like a 3d model or a 2d sprite) then you need to send a raycast.

The Object Oriented and (mostly) sane thing to do is to send a message from a camera script, and have all clickable objects have an OnClick function.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
	
	void Update() {

		if (Input.GetMouseButtonDown(0)) {
			RaycastHit hit;
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			
			if (Physics.Raycast(ray, out hit, 100f)) {
				// We DontRequireReceiver in the case that you click on something that isnt actually clickable.
				hit.collider.gameObject.SendMessage("OnClick", SendMessageOptions.DontRequireReceiver);
			}
		}
	}
}

public class ObjectA : MonoBehaviour {

	public void OnClick() {
		// do stuff for ObjectA
	}
}

public class ObjectB : MonoBehaviour {

	public void OnClick() {
		// do stuff for ObjectB
	}
}