Unity3d点击物体弹窗显示物体名称

160 阅读1分钟
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ClickShow : MonoBehaviour
{
    public GameObject UIPanel;
    // Start is called before the first frame update
    void Start()
    {
        UIPanel.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            bool raycast = Physics.Raycast(ray, out hit);
            if (raycast)
            {
                GameObject go = hit.collider.gameObject;
                
                Debug.DrawLine(ray.origin, hit.point);
                //必须是ClickObject下面的子物体点击才生效
                if(go.transform.parent.gameObject&&go.transform.parent.gameObject.name== "ClickObject")
                {
                    Debug.Log("打印物体的名称---------------");
                    Debug.Log(go.name);
                    //设置panel的位置,为鼠标点击的位置
                    //UIPanel.transform.position = Input.mousePosition;
                    UIPanel.transform.position = new Vector3(Input.mousePosition.x + 100, Input.mousePosition.y + 100, Input.mousePosition.z);
                    UIPanel.SetActive(true);
                    //根据UIPanel中的名字获取到text,设置内容
                    UIPanel.transform.Find("NameText").gameObject.GetComponent<Text>().text = go.name;
                }
            }
        }
    }
}