unity-game-engine

Omit all Debug.Asserts in play mode


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?


Solution

  • 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 ProjectSettingsPlayerScripting Define Symbols

    enter image description here

    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:


    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

    enter image description here

    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.