Last active
January 4, 2026 14:33
-
-
Save unitycoder/8999e08e03ceafb37ffea0cefe333d12 to your computer and use it in GitHub Desktop.
Unity Editor Add Custom MainToolbar button for Build and Run and Enter Playmode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Diagnostics; | |
| using System.IO; | |
| using System.Threading; | |
| using UnityEditor; | |
| using UnityEditor.Toolbars; | |
| using UnityEngine; | |
| using Debug = UnityEngine.Debug; | |
| public class BuildAndPlay | |
| { | |
| [MainToolbarElement("Tools/BuildsAndPlay", defaultDockPosition = MainToolbarDockPosition.Middle)] | |
| public static MainToolbarElement BuildAndPlayNow() | |
| { | |
| var icon = EditorGUIUtility.IconContent("BuildSettings.Standalone").image as Texture2D; | |
| var content = new MainToolbarContent(icon); | |
| return new MainToolbarButton(content, () => | |
| { | |
| // now enter playmode | |
| EditorApplication.isPlaying = true; | |
| // call build and run | |
| BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); | |
| // take scenes from build settings | |
| var scenes = new System.Collections.Generic.List<string>(); | |
| foreach (var scene in EditorBuildSettings.scenes) | |
| { | |
| if (scene.enabled) | |
| { | |
| scenes.Add(scene.path); | |
| } | |
| } | |
| string relativeBuildPath = "../Builds/pc/Project.exe"; | |
| buildPlayerOptions.scenes = scenes.ToArray(); | |
| buildPlayerOptions.locationPathName = relativeBuildPath; | |
| buildPlayerOptions.target = BuildTarget.StandaloneWindows64; | |
| buildPlayerOptions.options = BuildOptions.None; | |
| BuildPipeline.BuildPlayer(buildPlayerOptions); | |
| // TODO add delay if needed? (exe hangs often?) | |
| try | |
| { | |
| // TODO add amount of clients to run | |
| // After build is complete, run the built application | |
| var exepath = Path.Combine(Application.dataPath, "..", "Builds", "pc", "Project.exe"); | |
| Process.Start(exepath); | |
| } | |
| catch (System.Exception e) | |
| { | |
| Debug.LogException(e); | |
| throw; | |
| } | |
| }); | |
| } // BuildAndPlayNow | |
| } // class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment