Assert 类包含用于在代码中设置不变量的断言方法。
All method calls will be conditionally included only in a development
build, unless specified explicitly. See BuildOptions.ForceEnableAssertions.
The inclusion of an assertion is controlled by the UNITY_ASSERTIONS
define.
一个断言方法的失败不会中断执行的控制流程。
失败时,系统会将断言消息记录在日志中 (LogType.Assert),而执行
会继续进行。如果 Assert.raiseExceptions 设置为 true,则系统会抛出 AssertionException
而不是将消息记录在日志中。
如果调试器附加到项目(System.Diagnostics.Debugger.IsAttached 为 true),则系统会抛出
AssertionException 以暂停执行并
调用调试器。
using UnityEngine; using UnityEngine.Assertions;
public class AssertionExampleClass : MonoBehaviour { public int health; public GameObject go;
void Update() { // You expect the health never to be equal to zero Assert.AreNotEqual(0, health);
// The referenced GameObject should be always (in every frame) be active Assert.IsTrue(go.activeInHierarchy); } }
raiseExceptions | Unity 是否应在失败时抛出异常。 |
AreApproximatelyEqual | Assert the values are approximately equal. |
AreEqual | Assert that the values are equal. |
AreNotApproximatelyEqual | Asserts that the values are approximately not equal. |
AreNotEqual | Assert that the values are not equal. |
IsFalse | Return true when the condition is false. Otherwise return false. |
IsNotNull | Assert that the value is not null. |
IsNull | Assert the value is null. |
IsTrue | 断言条件是 true。 |