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.
Answer by Nikunj-Kareliya · Sep 13, 2015 at 10:51 AM
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 !
As you are developing 2D game use 'Raycast2D' ins$$anonymous$$d of 'Raycast'.
$$anonymous$$ore better way is to use Unity UI for buttons like things..
Answer by shanta3220 · Feb 25, 2018 at 07:25 AM
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");
}
Another 2D Solution is to use OverlapPoint:
private void Update(){
if (Input.Get$$anonymous$$ouseButtonDown(0)) {
Vector3 pos = Input.mousePosition;
Collider2D hitCollider = Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(pos));
if (hitCollider != null && hitCollider.CompareTag ("Player")) {
Debug.Log("This is player");
}
}
Your answer
Follow this Question
Related Questions
Raycast not detecting hit 4 Answers
How to freeze an GameObject on x axis in specific direction? 1 Answer
Adding collision to Raycast hit 0 Answers
Make raycast ignore hitbox? 0 Answers
Restrict held object movement 0 Answers