在游戏开发中,我们通常会为了防止用户同时打开多个端口,进行一些处理。大概的逻辑就是,首先判断有没有端口已经打开,如果有,则关闭将要打开的端口,如果没有,则打开端口。这里只是在Window下进行的操作,下面是具体实现: 【AppleScript】 #if UNITY_STANDALONE_WIN using System; using System.Diagnostics; using System.Threading; using System.Runtime.Interopservices; #endif using System.Collections; /// <summary> /// 防止同时运行多个实例 /// 用于检查此应用程序是否有多个存在,当检测到另一个实例已在运行,并退出当前的应用程序 /// 仅限于Windows(其他平台由相应的操作系统处理) /// </summary> public class PreventMultipleExecution : MonoBehaviour { public string m_WindowCaption = string.Empty; public string m_WindowClass = "UnityWndClass"; #if UNITY_STANDALONE_WIN //引用Win32 API [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); //创建指定窗口的线程设置到前台,并且激活该窗口 [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); //设置指定窗口的显示状态。 [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); //确定给定窗口是否是最小化(图标化)的窗口。 [DllImport("user32.dll")] private static extern IntPtr FindWindow(string className, string windowName); //检索处理顶级窗口的类名和窗口名称匹配指定的字符串 // private static PreventMultipleExecution m_Instance = null; private System.Threading.Mutex m_Mutex = null; void Awake () { if (m_Instance != null) { Destroy(this.gameObject); return; } m_Instance = this; UnityEngine.Object.DontDestroyOnLoad(this); if (IsAlreadyRunning()) { //bring the original instance to front BringToFront(); Application.Quit(); } } /// <summary> /// 应用退出操作 /// </summary> void OnApplicationQuit() { if (m_Mutex != null) m_Mutex.ReleaseMutex(); } /// <summary> /// 判断应用是否已经运行 /// </summary> /// <returns></returns> private bool IsAlreadyRunning() { //create our mutex bool createdNew; m_Mutex = new System.Threading.Mutex(true, m_WindowCaption, out createdNew); if (!createdNew) m_Mutex = null; return (createdNew == false); //如果没有创建新的应用,说明已经有一个应用在运行 } /// <summary> /// 将应用实例窗口置于前面 /// </summary> private void BringToFront() { if (string.IsNullOrEmpty(m_WindowCaption)) return; const int SW_RESTORE = 9; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); IntPtr hWnd = FindWindow(string.IsNullOrEmpty(m_WindowClass) ? null : m_WindowClass, m_WindowCaption); if (hWnd == INVALID_HANDLE_VALUE) return; if (IsIconic(hWnd)) ShowWindow(hWnd, SW_RESTORE); SetForegroundWindow(hWnd); } #endif } |
Unity中防止多个客户端同时打开
最新推荐文章于 2025-07-29 09:56:40 发布