I have many pre-conditions and post-conditions, some of which are quite expensive.
I know they get stripped on actual builds, but can I toggle the asserts on and off in play mode?
The docs say the asserts are only invoked if UNITY_ASSERTIONS symbol is defined. How to I define/undefine that?
The docs say the asserts are only invoked if UNITY_ASSERTIONS symbol is defined. How to I define/undefine that?
In general you do that in the ProjectSettings
→ Player
→ Scripting Define Symbols
HOWEVER the UNITY_ASSERTIONS
define is actually controlled internally by BuildOptions.ForceEnableAssertions
so you should not add this manually.
Also afaik in PlayMode within the Editor the assertions are always enabled anyway.
But you could use the way of adding a global define above in the Scripting Define Symbols
the other way round like adding IGNORE_ASSERTS
and then simply do
#if !IGNORE_ASSERTS
Assert.IsTrue(false, "not true");
#endif
Note:
If you have/need multiple defines there separate the entries using a ;
.
This requires always a recompilation so this is not really an option for switching the asserts on and of in PlayMode .. you rather have to wait until the code is recompiled and restart playmode.
A complete alternative that works on runtime might be to simply implement a global script like
using UnityEditor;
public static class AssertionManager
{
// make it true by default so
public static bool enabled = true;
[MenuItem("Assertions/Enable Assertions", true)]
private static bool CanEnable()
{
return !enabled;
}
[MenuItem("Assertions/Enable Assertions")]
private static void Enable()
{
enabled = true;
}
[MenuItem("Assertions/Disable Assertions", true)]
private static bool CanDisable()
{
return enabled;
}
[MenuItem("Assertions/Disable Assertions")]
private static void Disable()
{
enabled = false;
}
}
This hast to be placed in a folder called Editor
so it is later excluded from the build. This adds a custom Menu to the top bar of Unity where you can now simply turn the Assertion on and of
and then in your scripts everywhere use
#if UNITY_EDITOR
if(AssertionManager.enabled)
#endif
Assert.IsTrue(false, "not true");
in order to in the editor use the AssertionManager
setting and later in a build use whatever is defined in the build settings.