Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Last active March 15, 2024 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nekomimi-daimao/f3c9c769c6875183987682c308f8212d to your computer and use it in GitHub Desktop.
Save nekomimi-daimao/f3c9c769c6875183987682c308f8212d to your computer and use it in GitHub Desktop.
DefineSwitcher - switch #define in unity
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Build;
using UnityEngine;
namespace Nekomimi.Daimao
{
/// <summary>
/// Switch #define.
/// rewrite <see cref="Define"/> and <seealso cref="DefineMenuPath"/>
/// </summary>
public class DefineSwitcher : IActiveBuildTargetChanged
{
#region Define
private const string Define = "UNITY_OVR";
private const char Separator = ';';
private static void SetDefine(bool on)
{
if (on == IsDefined())
{
return;
}
var current = new HashSet<string>(CurrentDefines());
if (on)
{
current.Add(Define);
}
else
{
current.Remove(Define);
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(
EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(Separator.ToString(), current)
);
}
private static IEnumerable<string> CurrentDefines()
{
return PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup).Split(Separator);
}
private static bool IsDefined()
{
return CurrentDefines().Contains(Define);
}
#endregion
#region EditorMenu
private const string DefineMenuPath = "Oculus/" + Define;
[MenuItem(DefineMenuPath, priority = -1)]
private static void SwitchDefine()
{
var current = IsDefined();
SetDefine(!current);
SetCheckState(!current);
}
private static void SetCheckState(bool state)
{
var check = Menu.GetChecked(DefineMenuPath);
if (state == check)
{
return;
}
Menu.SetChecked(DefineMenuPath, !check);
}
#endregion
#region IActiveBuildTargetChanged
public int callbackOrder { get; } = 0;
public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget)
{
SetCheckState(IsDefined());
}
#endregion
#region InitializeOnLoadMethod
private class FirstLoad : ScriptableSingleton<FirstLoad>
{
[SerializeField]
public bool AlreadyLoaded = false;
}
[InitializeOnLoadMethod]
private static void CheckOnLaunch()
{
if (FirstLoad.instance.AlreadyLoaded)
{
return;
}
FirstLoad.instance.AlreadyLoaded = true;
SetCheckState(IsDefined());
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment