新建一個Cube物體和一個腳本Cube,將Cube腳本掛到Cube物體上,代碼如下:
- using UnityEngine;
- using System.Collections;
- public class Cube : MonoBehaviour
- {
- void OnTouched()
- {
- Debug.Log("該物體被選中了!");
- }
- }
新建一個空物體,命名爲TouchManager,新建一個腳本TouchManager,將該腳本掛到空物體上,代碼如下:
- using UnityEngine;
- using System.Collections;
- public class TouchManager : MonoBehaviour
- {
- public Camera cam;
- private float timeHit = 0f; //用於點擊的時間間隔,每次點擊時間間隔應大於0.2秒
- void Update()
- {
- timeHit += Time.deltaTime;
- if (timeHit > 0.2f)
- {
- if (Input.GetMouseButton(0))
- {
- timeHit = 0f;
- RaycastHit hit;
- bool isHit = Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, 100f);
- if (isHit)
- {
- hit.collider.gameObject.SendMessage("OnTouched", SendMessageOptions.DontRequireReceiver);
- }
- }
- }
- }
- }
OK,完成!