Unity Script to Reset Idle Games at Shows

By Eric Lathrop on

After showing a game at a trade show/gallery/festival, I've noticed a problem where people walk away from a game mid-session. This makes it so the next person to walk up will start the game half-way through and miss the beginning, which often includes tutorials or learning moments. To make sure a demo restarts, I wrote this Unity script that fires an event when no inputs have been received for a set amount of time:

using System;
using UnityEngine;
using UnityEngine.Events;

public class IdleTimer : MonoBehaviour {

  public float secondsToWait = 7;
  private float elapsed;

  [Serializable]
  public class IdleEvent : UnityEvent<GameObject> { }

  public IdleEvent onIdle;

  void Update() {
    // There was a  case where you could hit the home button on a device, then come back to the game and it would see a huge delta, causing it to return back to the menu unexpectedly.
    elapsed += Mathf.Clamp(Time.deltaTime, 0f, 1f/30f);

    if (Input.anyKey || Input.touchCount > 0) {
      elapsed = 0;
    }
    if (elapsed > secondsToWait) {
      onIdle.Invoke(gameObject);
      enabled = false;
    }
  }
}