unity3d 触发guitexture 鼠标点击事件

在unity3d创建了guitexture后,如何响应鼠标点击事件,

1、为maincamera添加guilayer(一般不用自己添加,在添加maincamera时会自动创建对应的guilayer)

2、在脚本代码中读取对应的guilayer

3、检测鼠标或触摸屏单击事件,使用HitTest检测是否被点击

4、根据名称执行对应的函数


unity3d 触发guitexture 鼠标点击事件_第1张图片

private GUILayer test;//定义

 void Start()
        {
            test = Camera.main.GetComponent<GUILayer>();//获取主摄像机对应的guilayer
	}

void Update()
        {
            if (Input.touchCount > 0 ||
                Input.GetMouseButtonDown(0))//鼠标或触摸事件
            {                

                if (test.HitTest(Input.mousePosition) != null)//点击检测到guitexture
                    Debug.Log(test.HitTest(Input.mousePosition).name);//调试输出guitexture的名称

            }
        }

官方文档:

GUILayer.HitTest

GUIElement HitTest(Vector3 screenPosition);
Description

Get the GUI element at a specific screen position.

Returns the GUIElement at a specific point on screen. If screenPosition is inside some GUIElement,that element is returned. Returns null if the position is not inside any GUI element.GUI elements that belong to Ignore Raycast layer will be ignored, as if they would not exist.

screenPosition is measured in screen coordinates, like the values returned by Input.mousePosition property.

Note: GUILayer.HitTest only finds old-school GUI components(made up of the classes GUIElement, GUITexture, GUIText, GUILayer),and will not work with the "new" one (referred to as "UnityGUI" andmade up of all the other GUIAnything classes, and the OnGUI() call).
So if you're using UnityGUI, HitTest won't find anything.

See Also: GUIElement.HitTest, Input.mousePosition.
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    private GUILayer test;
    void Update() {
        if (test.HitTest(Input.mousePosition) != null)
            Debug.Log(test.HitTest(Input.mousePosition).name);
        
    }
    void Example() {
        test = Camera.main.GetComponent<GUILayer>();
    }
}

你可能感兴趣的:(unity3d 触发guitexture 鼠标点击事件)