Prevent game from running twice if it is already running

Godot Version

4.5

Question

Hi guys, i wanted to know if there is a way to stop my game from running twice, like if a player already opened and run the game they shouldn’t be able to open the game again and have two window running the same game.
I think I can just create a file when game start and delete it when game is closed and in start check if that file exists or not. Is there any better solution?
Thank you.

As far as I know, there’s no “one size fits all” solution to this, but you can do multiple things to achieve this, but I used the following one before:

As you also mentioned, you can implement a file lock system, where as soon as your game starts, you create a hidden lock file (it can just be a simple file with a specific name, starting with a dot so it’s hidden for the user), and remove said file when the game exist. Then, you can check if that file exists on startup, and if it does, simply close the game. During the game, you should write the current timestamp in said file, so if your game crashes, and the file is not properly deleted, the next time your player tries to launch the game and the file is there, it can be checked, and see how old the timestamp is! If it’s too old, you can simply launch the game as normal and start writing the new timestamp in the lock file.

2 Likes

Why do you want to do this? What problem are you trying to solve? There might be an easier way to solve your problem.

Thank you, i was wondering how to handle crashing and force quit. You saved me

1 Like

Tibaverus’ solution seems to work for me but if you are wondering… my game involves a character (like some sort of desktop pet or assistance) that runs on a transparent window.
It would be bad to have two of a same character open at same time because it can ruin the story, also the game try to change and read game files so it would be bad if player try to run two instance of the game in same time.
I don’t think a normal player would try to run a game twice but i can’t trust them not to try that

1 Like

Valid use case and his approach is the one I would recommend. I just ask because if you were worried about hacking then that’s not a good approach.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.