unity打包出的EXE只能单例打开,不能多开。

一、代码实现
using
System; using System.Diagnostics; using System.Runtime.InteropServices; using UnityEngine; /// <summary> /// 防止同时运行多个实例 /// 用于检查此应用程序是否有多个存在,当检测到另一个实例已在运行,并退出当前的应用程序 /// 仅限于Windows(其他平台由相应的操作系统处理) /// </summary> public class PreventMultipleExecution : MonoBehaviour { public static PreventMultipleExecution instance; // bool unrun=false; [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)] public static extern int MessageBox(IntPtr handle, String message, String title, int type); void Awake() { #if !UNITY_EDITOR if (PreventMultipleExecution.instance != null) { Destroy(gameObject); return; } instance = this; DontDestroyOnLoad(gameObject); string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; UnityEngine.Debug.Log(strProcessName); Process[] app = Process.GetProcessesByName(strProcessName); if (app.Length > 1) { UnityEngine.Application.Quit(); MessageBox(IntPtr.Zero, "程序正在运行中", "警告", 0); return; } #endif } }

二、方法二:更简单的方法:直接unity中Player Setting

image

 

 

 

posted on 2026-04-25 16:59  juaa  阅读(19)  评论(0)    收藏  举报