How do you detect a mouse button click on a Game Object? C#

Hello,

I was making a 2D platformer in which you could press the “retry” button to restart the game. I looked around for a few guides but they all seemed to either be in javascript, or were outdated. I read a specific guide which tells you to use raycasts in order to detect whether or not a gameobject is clicked. However, my code did not work.

void Update (){
	if (Input.GetMouseButtonDown (0)) {
		RaycastHit hit;
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

		if(Physics.Raycast (ray, hit))
		{
			if(hit.transform.name == "Player")
			{
				Debug.Log ("Logged");
			}
		}
	}

What is wrong with this and how can it be fixed? I am aware that the variable “hit” is nothing at the moment, but I do not know how to assign raycasthit variables. Any help would be greatly appreciated.

Also, it seems that the syntax for Physics.Raycast changed, or I do not understand it properly. In the scripting API it says Raycast(Vector3 origin, Vector3 direction), but most guides on the internet use “hit” as their second parameter. If anyone could explain this, it would be appreciated.

Make sure, you use ‘out hit’ as a argument, in C#.

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;

if(Physics.Raycast (ray, out hit))
{
     if(hit.transform.name == "Player")
     {
         Debug.Log ("This is a Player");
     }
     else {
         Debug.Log ("This isn't a Player");                
     }
}

PS. use tags instead of compare game object names !

Although this is late, if anybody is curious of how to do it with RaycastHit2D for your 2D game. (make sure to set main camera to Orthographic).

RaycastHit2D hit = Physics2D.Raycast(new Vector2(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).x, Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).y), Vector2.zero, 0);
if (hit) {
	if (hit.collider.CompareTag("Player")) {
        	Debug.Log("This is player");
}