Search Unity

Wrapping Debug.Assert and skip wrap method in the stack trace

Discussion in 'Scripting' started by kevin-masson, Aug 7, 2019.

  1. kevin-masson

    kevin-masson

    Joined:
    Sep 24, 2018
    Posts:
    73
    I'm trying to wrap Debug.Assert() into multiple functions to allow the following:
    - have 2 type of asserts (Release: always enabled, Dev: enabled in the editor and in the build when a specific flag is set)
    - set a default assert message containing the LOC related to the error using `CompilerServices.
    CallerFilePath` and `CompilerServices.CallerLineNumber`

    So far, i have the following:

    Code (CSharp):
    1. using System.Diagnostics;
    2.  
    3. public static class Asserts
    4. {
    5.     /// <summary>Runtime and editor asserts. These will always be executed.</summary>
    6.     /// <param name="context">The object attached to this assert. Unused in web builds.</param>
    7.     public static void ReleaseAssert(bool condition, string message, UnityEngine.Object context = null)
    8.     {
    9.         #if UNITY_EDITOR
    10.         UnityEngine.Debug.Assert(condition, message, context);
    11.         #elif !UNITY_EDITOR && UNITY_WEBGL
    12.         UnityEngine.Debug.Assert(condition, message);
    13.         #else
    14.         UnityEngine.Debug.Assert(false, "RealseAssert case not supported.");
    15.         #endif
    16.     }
    17.  
    18.     /// <summary>Asserts that are executed only for deveveloppers or when ALL_ASSERTS build flag is specified.</summary>
    19.     [Conditional("UNITY_EDITOR"), Conditional("ALL_ASSERTS")]
    20.     public static void Assert(bool condition, string message, UnityEngine.Object context)
    21.     {
    22.         UnityEngine.Debug.Assert(condition, message, context);
    23.     }
    24.  
    25.     /// <summary>Asserts that are executed only for deveveloppers or when ALL_ASSERTS build flag is specified.</summary>
    26.     [Conditional("UNITY_EDITOR"), Conditional("ALL_ASSERTS")]
    27.     public static void Assert(bool condition, string message)
    28.     {
    29.         UnityEngine.Debug.Assert(condition, message);
    30.     }
    31. }
    32.  
    But there is only one problem i need to resolve. By wrapping `Debug.Assert` the message logged in the editor console does not redirect to the correct part of the code. It redirect to `Asserts.RealaseAssert` or `Asserts.Assert` but i would like it to redirect to the parent method that called my wrapper.

    I found some interesting things like `StackTrace.METHODS_TO_SKIP` or the `StackTrace` constructor that allows you to give a number of `StackFrame` (method) to skip. But I am not able to log the stack trace with a link to the code.

    I also tried to inline my methods with `AggressiveInlining` but it does not change anything.

    Do you have any idea of how to fix this ?
     
  2. kevin-masson

    kevin-masson

    Joined:
    Sep 24, 2018
    Posts:
    73