how to detect which gameobject is clicked

爷,独闯天下 提交于 2020-04-17 20:30:48

问题


I want to know which gameobject is clicked with mouse on a 2D project

I used

 void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            clickTime = DateTime.Now;
            mousePosition = Input.mousePosition;

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);

            if (hit != null && hit.collider != null)
            {


            }

        }
}

but it never goes in the second if condition

EDIT: I am working on a single script and access all gameobject from there using GameObject.FindGameObjectWithTag() and as I understand thats why the collider code in main script doesnt triggered. I added a screenshot my code is in GameObject


回答1:


Consider using OnMouseOver() method (docs):

private void OnMouseOver() {
    if (!Input.GetMouseButtonDown(0)) return;

    // Your logic here.
}

This method only works with collider attached to gameobject, just like Raycast.

It would be cleaner and slightly more performant because there are no multiple Update() methods to iterate each frame. Something to keep in mind if you have dozens or hundreds of clickable objects.

(Although there are reports that this method doesn't work with multiple cameras one of which is ortographic one, in which case it is not an option for you.)




回答2:


This method works perfect on both desktop and mobile apps:

  1. Add a collider component to each object you want to detect its click event.
  2. Add a script to your project (let's name it MyObject.cs). This script must implement the IPointerDownHandler interface and its method. And this script must add the Physics2DRaycaster to the camera. The whole body of this script could be like this:

    public class MyObject : MonoBehaviour, IPointerDownHandler
    {
        private void Start()
        {
            AddPhysics2DRaycaster();
        }
    
        public void OnPointerDown(PointerEventData eventData)
        {
            Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
        }
    
        private void AddPhysics2DRaycaster()
        {
            Physics2DRaycaster physicsRaycaster = FindObjectOfType<Physics2DRaycaster>();
            if (physicsRaycaster == null)
            {
                Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
            }
        }
    }
    
  3. Add the MyObject.cs script to every object you want to detect click on it. After that, when you click on those objects, their name will display on Console.

  4. Make sure that EventSystem exists in your project's Hierarchy. If not, add it by right click.

P.S. The MyObject.cs script now has IPointerDownHandler. This detects click as soon as you touch the objects. You also can use IPointerUpHandler and IDragHandler for different purposes!

and sorry for my bad English.




回答3:


When you use a raycast you should set a collider on your sprite

private void Update()
{
   if (Input.GetMouseButtonDown(0))
   {
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);

      if (hit.collider != null) {
         Debug.Log ("CLICKED " + hit.collider.name);
      }
   }
}

This is working for me in unity 5.6

Note: "LeftClick" is just a "GameObject" nothing else, I called it like this for better identification :)


EDITED

I test this method for UI button but its not working; so i used a different approach. For UI button you can add a listener like this:

GameObject.Find ("YourButtonName").GetComponent<Button> ().onClick.AddListener (() => {

});


来源:https://stackoverflow.com/questions/60666526/how-to-detect-which-gameobject-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!