初學unity3D,對於其中的事件響應不是很清楚,於是寫了下面的代碼來驗證:
1、新建.cs文件,名為testMouse.cs:
- using UnityEngine;
- using System.Collections;
- public class testMouse : MonoBehaviour {
- // Use this for initialization
- void Start () {
- }
- // Update is called once per frame
- void Update () {
- if (Input.GetMouseButtonDown(0))
- {
- Debug.Log("Input.GetMouseButtonDown response");
- }
- }
- void OnMouseDown() {
- Debug.Log("OnMouseDown response");
- }
- void OnGUI() {
- if (Event.current != null && Event.current.type == EventType.mouseDown) {
- Debug.Log("EventType.mouseDown response");
- }
- }
- }
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函數在每幀會被調用多次。