- Home /
how to detect if there is an instance of my game already running?
player is able to launch the game [standalone executable PC/Mac] multiple number of times.
I should make sure only 1 istance of my game is running at once. I can quit from the game at startup, but i don't know how to detect if an other isntace of my game is already running.
Answer by CinnaMint · Dec 04, 2011 at 08:17 AM
(I know this is old, but here might be an answer. It's not the right answer, but it explains something).
As far as I know, there is no way to accurately deal with this. I myself have needed a solution for this, but both options are marred.
First, Unity 3 Standalone's on Windows platform are -SUPPOSED- to have a command line that you can type in to force the game to only run one instance. It's as follows:
GameName.exe -single-instance
Theoretically, if the game is started again, it will find the current process and switch focus to it instead. However, I haven't got that command line attribute to work, or any other Windows ones (Such as -popupwindow). So I went on to try something else...
System.Diagnostics.Process.GetProcessesByName("name");
System.Diagnostics.Process.GetProcesses();
The System.Diagnostics.Process namespace in .NET contains a lot of nice little goodies. Such as the ability to search currently running processes on a machine for one of a particular name (GetProcessByName), or give a list of all currently running processes (GetProcesses) so you can search if your Game's process is already running, and kill the game before THAT version loads.
However, the Mono version currently included in Unity is actually an older version, which contains a bug. So any use of those two aforementioned functions within System.Diagnostics.Process will give Exception Errors for no reason.
Using GetProcesses() returns an array of currently running processes, but getting anything but the PID of the process returns an Exception error, saying the process has exited (But it hasn't).
Using GetProcessByName() won't go anywhere, either, and gives the same error.
So... In short, I've found out that you cannot check if your game, or anything else is running.
Hey! After more that a decade I come to say that "System.Diagnostics.Process will give Exception Errors for no reason" this was fixed in newer versions of Unity and this method works now! Also here's a function to check:
bool IsAlreadyRunning()
{
int count = 0;
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process process in processes)
{
if (process.ProcessName == Consts.processName)
{
count++;
if (count > 1)
return true;
}
}
return false;
}