How to get GameObject that is clicked by a mouse?

Hi, how can i get the GameObject that is clicked by a mouse by storing it in a variable?
in example:

GameObject x;

now how do i send the Object i clicked into x?
I can put

void OnMouseDown(){
Sendmessage(“UpdateObject”, this.gameObject);

on all object, but it would be kind of a pain, is there any easier way to know what object is being clicked and how to point into that object?
Sorry for the awful english

Using a Raycast from your camera is the best option. The RayCastHit that is used in conjunction with a RayCast will return information about the collider that was hit, including the transform:

void Update()
    if( Input.GetMouseButtonDown(0) )
		Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
		RaycastHit hit;
		if( Physics.Raycast( ray, out hit, 100 ) )
            Debug.Log( );

You will notice that I accessed the transform, then the gameObject. The gameObject I believe isn’t returned with the RayCastHit, but the gameObject is an inherited member of the transform that is returned.

I realize this is an old post, but I wonder if there’s a programmatic reason not to do it as follows:

  • Put OnMouseDown/Drag/up in the to-be-clicked object itself.
  • Put the actions to be done on clicked object either in the to-be-clicked object itself OR in GameControl.



public class GameControlScript : MonoBehaviour {

    public GameObject clickedGameObject;

    public void DoSomethingToClicked(GameObject clickedOn) {
        clickedGameObject = clickedOn;
        // Do things with clickedGameObject;
    }// end DoSomethingToClicked


public class ObjectScript : MonoBehaviour {
    public GameControlScript control; 

void Start () {
    control = GameObject.Find("GameControl").GetComponent<GameControlScript>();
}// end start

void OnMouseUp() {
}//end OnMouseUp