Skip to content

Instantly share code, notes, and snippets.

@benbenmushi
Last active May 13, 2020 10:21
Show Gist options
  • Save benbenmushi/b51e65093271c3ae8058dc9ee8a6b051 to your computer and use it in GitHub Desktop.
Save benbenmushi/b51e65093271c3ae8058dc9ee8a6b051 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEditor.Callbacks;
using UnityEditor.Build;
using UnityEditor;
using UnityEditor.Build.Reporting;
public class BuildOnlyDefine : IPreprocessBuildWithReport, IPostprocessBuildWithReport
{
int IOrderedCallback.callbackOrder => 1;
public static string runtimeOnlyDefines = "UNITY_RUNTIME"; // example of multiple defines: "UNITY_RUNTIME;UNITY_NOT_EDITOR"
static BuildTargetGroup currentTarget
{
get
{
#if UNITY_STANDALONE
return BuildTargetGroup.Standalone;
#elif UNITY_ANDROID
return BuildTargetGroup.Android;
#elif UNITY_IOS
return BuildTargetGroup.iOS;
#endif
}
}
// CALLED BEFORE THE BUILD
public void OnPreprocessBuild(BuildReport report)
{
Debug.Log("BuildOnlyDefine: before build: adding symbols: " + runtimeOnlyDefines);
// Start listening for errors when build starts
Application.logMessageReceived += OnBuildError;
string str = PlayerSettings.GetScriptingDefineSymbolsForGroup(currentTarget);
PlayerSettings.SetScriptingDefineSymbolsForGroup(currentTarget, str + ";" + runtimeOnlyDefines);
AssetDatabase.Refresh();
}
// CALLED DURING BUILD TO CHECK FOR ERRORS
private void OnBuildError(string condition, string stacktrace, LogType type)
{
if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert)
{
Debug.Log("BuildOnlyDefine: Error message received during build process");
// FAILED TO BUILD, CALL POSTPROCESS ANYWAY
OnPostprocessBuild(null);
}
}
// CALLED AFTER THE BUILD
public void OnPostprocessBuild(BuildReport report)
{
Debug.Log("BuildOnlyDefine: after build: removing symbols: " + runtimeOnlyDefines);
// IF BUILD FINISHED AND SUCCEEDED, STOP LOOKING FOR ERRORS
Application.logMessageReceived -= OnBuildError;
string str = PlayerSettings.GetScriptingDefineSymbolsForGroup(currentTarget);
PlayerSettings.SetScriptingDefineSymbolsForGroup(currentTarget, str.Replace(runtimeOnlyDefines, ""));
AssetDatabase.Refresh();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment