i want to check if the user clicked in one of my game object(i have 15 game objects), if the user does not clicked in one of them for 10 seconds display a text and if he clicked in one of my game objects he can continue playing.
CodePudding user response:
Here's the code:
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;
}
}
Try unitypackage if you want to see how it works.