unity3d 觸發guitexture 滑鼠點擊事件

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.