Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active January 4, 2026 14:33
Show Gist options
  • Select an option

  • Save unitycoder/8999e08e03ceafb37ffea0cefe333d12 to your computer and use it in GitHub Desktop.

Select an option

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
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