- Home /
Is there a way to ignore code depending on assets that are imported into the project?
I am looking for a way to ignore certain pieces of code depending on which packages are loaded into the project. Like the #if UNITY_EDITOR, but instead of checking the platform, it should be checking packages. For example: if I import the SteamVr support packages, only the code using that packages should be used. But when I import Oculus VR support, it should only use code that uses that package.
thanks
Answer by jackmw94 · Nov 12, 2020 at 04:54 PM
I get a funny feeling about the prospect of managing defines like this. If you're annoyed that you have to do it manually often then you could have a little menu option to add / remove it for you? :
public static class DefineHelper
{
[MenuItem("Project/XYZ/Set defined")]
public static void SetXYZDefined() => SetUnsetDefine("XYZ", true);
[MenuItem("Project/XYZ/Remove define")]
public static void RemoveXYZDefined() => SetUnsetDefine("XYZ", false);
private static void SetUnsetDefine(string symbol, bool set)
{
var symbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
Debug.Log($"Original symbols: {symbols}");
bool symbolPresent = symbols.Contains(symbol);
if (symbolPresent == set)
{
Debug.Log($"Symbol was already {(set ? "present" : "excluded")}");
return;
}
if (set)
{
symbols = string.Concat(symbols, ",XYZ");
}
else
{
symbols = symbols.Replace("XYZ", "");
// not sure where this would have been in the string so account for each
symbols = symbols.Replace(",,", ",");
symbols = symbols.TrimStart(',');
symbols = symbols.TrimEnd(',');
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, symbols);
Debug.Log($"New symbols: {PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone)}");
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
}
}
This could then be easily extended to remove the alternatives when setting your chosen one if the defines are mutually exclusive :)
XYZ should be your own define you create for you different package code