我想檢查用戶是否點擊了我的一個游戲物件(我有 15 個游戲物件),如果用戶在 10 秒內沒有點擊其中一個,則顯示文本,如果他點擊了我的一個游戲物件,他可以繼續玩。
uj5u.com熱心網友回復:
這是代碼:
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// Attach this component to "your game objects" along with collider.
/// Also, you have to attach
/// - PhysicsRaycaster (for 3D)
/// - Physics2DRaycaster (for 2D)
/// to your Main Camera in order to detect Click.
/// </summary>
public class ClickDetector : MonoBehaviour, IPointerClickHandler
{
void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
{
IdleDetector.NotifyClick();
}
}
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// You may want to attach this component to empty GameObject.
/// You need only one instance of this component in the scene.
/// </summary>
public class IdleDetector : MonoBehaviour
{
[SerializeField] float _timeoutSeconds = 10;
[SerializeField] Text _console = default;
static float _timer = 0f;
static bool _isTimedout = false;
void Update()
{
_timer = Time.deltaTime;
if (_timer > _timeoutSeconds)
{
if (!_isTimedout)
{
// Show message.
string message = $"{_timeoutSeconds} seconds elapsed without click.";
Debug.Log(message);
if (_console)
{
_console.text = message;
}
_isTimedout = true;
}
// Do whatever you want on timeout.
}
else if (!_isTimedout && _console.text.Length > 0)
{
_console.text = "";
}
}
public static void NotifyClick()
{
Debug.Log("Click.");
_timer = 0f;
_isTimedout = false;
}
}
如果您想了解它是如何作業的,請嘗試 unitypackage。
- 統一包
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432322.html
下一篇:檢測方法外的變數
