Unity 5.1 断言库(Assertion Library)
发表于2017-08-29
Unity 5.1为开发者带来了全新的断言库,在 Asset 类中可以方便的找到需要使用断言的函数。本篇文章中,将会为大家介绍什么是断言库(ASSERTION LIBRARY),以及如何用它来提升游戏中运行错误的诊断效率。
使用断言可以让错误在产品“开发阶段”尽快的暴露,减少Debug的时间,这个阶段打开“断言”。“发布阶段”则关闭断言。
代码示例
using UnityEngine; //使用Assert类需要这个包 using UnityEngine.Assertions; public class Test : MonoBehaviour { //airport有可能为null public Airport airport; void Update() { //断言不为Null,如果为Null就会报错 //UnassignedReferenceException: The variable airport of Test has not been assigned. //You probably need to assign the airport variable of the Test script in the //inspector.Test.Update () (at Assets/Game/Scripts/Test/Test.cs:15) Assert.IsNotNull(airport); if (Vector3.Distance(airport.transform.position, transform.position) < 1000) { //Land(); } } // ... }
- 为需要设置一个宏,将断言功能打开。
如何设置宏开关 UNITY_ASSERTIONS
只是添加了这些代码断言还是没有产生作用,因为需要设置一个宏,将断言功能打开。
Unity宏设置:Edit -> Project Settings -> Player -> Scripting Define Symbols
如下图设置:宏可以添加多个,用分号隔开即可
设置以后,再运行unity的工程。既可以发现UnassignedReferenceException
的错误
控制台显示异常
如下图
如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引