Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Script to detect when system has gone to sleep

Discussion in 'Scripting' started by Kokowolo, Sep 23, 2021.

  1. Kokowolo

    Kokowolo

    Joined:
    Mar 26, 2020
    Posts:
    41
    I've looked around for this a bit and there doesn't seem to be any solid, working information out there. Essentially, I need a script that can detect when the OS has gone to sleep.

    I've tried using time measurements with Unity function calls but they seem unreliable for this task (OnApplicationFocus & OnApplicationPause don't really pertain to sleeping, or at least I couldn't figure something out). I've also tried using C# power level assessment, but I couldn't get that working either.
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,913
    There is no built-in functionality in Unity. You will need to call OS-functions for that. Those depend on the OS you're targeting.
     
  3. Kokowolo

    Kokowolo

    Joined:
    Mar 26, 2020
    Posts:
    41
    Any leads for how you would do that on MacOS and Windows builds?
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
  5. Kokowolo

    Kokowolo

    Joined:
    Mar 26, 2020
    Posts:
    41
    Hey @Joe-Censored! I tried that (and Time.unscaledTime) in between OnApplicationFocus & OnApplicationPause and while it has a little bit of success, it's not very reliable since the frame jump could have also been because the user was tabbed out of the application and did something that might have caused a frame spike.