-4
\$\begingroup\$

I've made a game with Unity and I want to execute a C# script that runs even the game was closed.

I searched a lot but didn't find anything.

\$\endgroup\$
  • 4
    \$\begingroup\$ Why would you want that? The user does not want your game to run on their device because they closed it, why would you go against their will? \$\endgroup\$ – Vaillancourt Jun 22 '19 at 12:02
  • 1
    \$\begingroup\$ Are you trying to achieve something like a simulation that continues to evolve while the player is away from the game? (eg. I plant a crop in game, then quit, then return the next day to find my crop has grown while I was away and is now ready to harvest). If so, this isn't done by running code on the client's device while the application is closed. It's usually a mix of saving timestamps and fast-forwarding the game's state on the next boot according to the amount of time since the last saved timestamp, or periodic updates on a server-side process. \$\endgroup\$ – DMGregory Jun 22 '19 at 14:29
2
\$\begingroup\$

I have not seen a way to do this in Unity, which makes sense. Unity is not developed to run as a service. However, it has something close. Look up Unity Application.runInBackground. You can couple this with the OnApplicationFocus event to determine the state. Normally a game just pauses in the background.

But for clarity, you are specifically asking about running code after the program has been closed. This is typically not done with Unity, but what most applications do, is pair the installation with a service that will run in the background. In general, it is considered a bad practice for user interest.

When user's discover your application is eating battery, bandwidth and processing cycles when not in use, they will assume it is for spying on them.

What more places might choose to do, is just execute something at the start or end of the programs execution. To capture the ending event, even when not done from a close button, use OnApplicationQuit. Then, using a timed event to announce things to a user, such as this one for Android.

Events are how many apps give notifications on mobile when not running. On exiting, the games will usually understand based on timing, when an event will occur. Such as building X will complete in 3 minutes and 41 seconds, or the next online game cycle starts at midnight.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ and what about android studio ,can i do ? \$\endgroup\$ – Oussama Sabri Jun 22 '19 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.