如何检测单击哪个游戏对象 [英] how to detect which gameobject is clicked

查看:93
本文介绍了如何检测单击哪个游戏对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在2D项目中用鼠标单击了哪个游戏对象

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

我用过

 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

我正在处理一个脚本,并使用GameObject.FindGameObjectWithTag()从那里访问所有游戏对象,并且据我所知,这就是为什么未触发主脚本中的对撞代码的原因. 我添加了一个屏幕截图,我的代码在GameObject中

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

推荐答案

使用光线投射时,应在子画面上设置碰撞器

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);
      }
   }
}

这对我来说是统一的5.6

This is working for me in unity 5.6

注意:"LeftClick"仅仅是一个"GameObject",我这样称呼它是为了更好地识别它:)

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

已编辑

我为UI按钮测试了此方法,但是它不起作用;所以我使用了不同的方法.对于UI按钮,您可以添加这样的侦听器:

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 (() => {

});

这篇关于如何检测单击哪个游戏对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆