unity3d 触发guitexture 鼠标点击事件

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

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

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

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

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



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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值