简体   繁体   中英

changing scene after a couple of minutes if the player did not clicked in the game scene

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM