Unity3D 中鼠標按下時OnMouseDown()、Input.GetMouseButtonDown()和EventType.MouseDown的響應驗證


初學unity3D,對於其中的事件響應不是很清楚,於是寫了下面的代碼來驗證:

1、新建.cs文件,名為testMouse.cs:

 

[csharp]  view plain  copy
 
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class testMouse : MonoBehaviour {  
  5.   
  6.     // Use this for initialization  
  7.     void Start () {  
  8.       
  9.     }  
  10.       
  11.     // Update is called once per frame  
  12.     void Update () {  
  13.         if (Input.GetMouseButtonDown(0))  
  14.         {  
  15.             Debug.Log("Input.GetMouseButtonDown response");  
  16.         }  
  17.     }  
  18.   
  19.     void OnMouseDown() {  
  20.         Debug.Log("OnMouseDown response");  
  21.     }  
  22.   
  23.     void OnGUI() {  
  24.         if (Event.current != null && Event.current.type == EventType.mouseDown) {  
  25.             Debug.Log("EventType.mouseDown response");  
  26.         }  
  27.     }  
  28. }  

 

2、場景中的游戲對象很簡單,只有一個Cube和主相機。

 

3、將testMouse.cs組件附加到Cube上面,運行游戲,當用鼠標點擊Cube時,會有如下顯示:

 

4、當用鼠標單擊任何除Cube外的位置都會產生如下響應:

 

 

5、這說明Event和Input.GetMousexxx事件會被任何gameobject監控到,而OnMousexxx事件只會被該腳本附加上的gameobject監控到。

 

6、為什么Event事件要寫在OnGUI函數里面呢?可以再這兩個文檔中找到線索:

a、http://game.ceeger.com/Script/MonoBehaviour/MonoBehaviour.OnGUI.html

b、http://game.ceeger.com/Script/Event/Event.html

OnGUI函數在每幀會被調用多次。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM