I really like Ntero’s solution and started adopting this approach in my code. However, I tend to want to spit out the values of offending variables in the message string, but this adds a lot of execution overhead with constant string concatenations taking place without the assertion actually being tripped.
I found that I could defer the string concatenations by using a delegate function that returns a string after the conditional fails. This afforded me roughly a 15x speedup in the assertion code and I simply had to get used to inserting “() =>” before each message string as shown below.
Here are two new Assert.Test method variations I added. The first is incredibly fast if you can drop the message altogether and simply rely on line numbers in the stack trace. My use of System.Func may seem a bit cryptic – you can substitute your own delegate type if you prefer.
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Test(bool comparison) {
if (!comparison) {
Debug.LogError("Assertion failed");
Debug.Break();
}
}
[System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Test(bool comparison, System.Func<string> strf) {
if (!comparison) {
Debug.LogError(strf());
Debug.Break();
}
}
Here is an example of how the assertion is made using a delegate function that returns a string:.
Assert.Test(i<=j j<=k, () => "Incorrect variable order -- i,j,k = " + i + ',' + j + ',' + k);
Then again, if execution speed is of prime importance, then you can’t afford even the method call to Assert.Test(). So nothing beats the speed of the following, with the downside that the #if / #endif pairs make the code a bit less readable. When the assertions are skipped, this runs about forty times faster than the string delegate on my system.
#if ASSERT
if (i > j || j > k) Assert.Throw("Incorrect variable order -- i,j,k = " + i + ',' + j + ',' + k);
if (i > j || j > k) Debug.LogError("Incorrect variable order -- i,j,k = " + i + ',' + j + ',' + k);
#endif