Unity assertions Unity 5.1 Assertion Library

Source: Internet
Author: User
Tags unity 5

Unity assertions Unity 5.1 Assertion Library
When you build a Unity mobile game, you are most likely eager to set Script Call Optimization to Fast But No limits, as long as you believe you can.

Fast But No restrictions tions are hidden in the Edit-> Project Settings-> Player menu (Other Settings/Optimization section ). By selecting this option, your code removes the exception handling code and achieves better performance. Enabling this option poses a high risk. From now on, any exception will cause your game to crash immediately, and you don't even know why.
You may want to enable the Fast But No Exceptions option, only when you are sure that your game will not throw a single exception. In addition, if you are not the only person to work in the project, the risk is even greater.
Do not assume anything
Do not assume that your script is correctly set. To be the worst possible situation for a pessimistic. Let's take this script as an example:

 

public class Plane : MonoBehaviour {    public Airport airport;    void Update() {        if (Vector3.Distance(airport.transform.position, transform.position) < 1000) {            Land();        }    }    // ...}

 

This is a very basic example of how to interact with an airport plane. I think you already know what to say. This code will be interrupted if there is no Airport. This is where we assume that the person who works in the scenario will carefully connect all references between objects. But it is not that easy, because all referenced Unity they do not connect will not give anyone any errors or warnings unless they run Scene and see exceptions.


Okay, let's try to make this script more self-conscious. We hope it sounds a bit faulty. To do this, I will use the MonoBehaviour. OnValidate () message.
When OnValidate () is called:

? You do not need to enter the play mode in the editor.
? When any script value is changed
? Scenario scene Loading


Therefore, the script may now look like this:

 

public class Plane : MonoBehaviour {    public Airport airport;    void OnValidate() {        if (airport == null) {            Debug.LogError("Airport is set to null", this);        }    }    void Update() {        if (Vector3.Distance(airport.transform.position, transform.position) < 1000) {            Land();        }    }    // ...}


This will print the error message to the console, playing your game in the editor, and in most cases this will be enough. However, you may also want to check whether the airport is null at runtime (the OnValidate () function only works in the editor ).

 

public class Plane : MonoBehaviour {    public Airport airport;    void OnValidate() {        CommonValidate();    }    void Update() {        CommonValidate();        if (Vector3.Distance(airport.transform.position, transform.position) < 1000) {            Land();        }    }    void CommonValidate() {        if (airport == null) {            Debug.LogError("Airport is set to null", this);        }    }    // ...}


Well, now you must not throw any exceptions in your game, causing some (small, but still) overhead for all the verification processes. How to get rid of it? Maybe the pre-processor will help?

 

public class Plane : MonoBehaviour {    public Airport airport;    void OnValidate() {        CommonValidate();    }    void Update() {#if UNITY_EDITOR        CommonValidate();#endif        if (Vector3.Distance(airport.transform.position, transform.position) < 1000) {            Land();        }    }    void CommonValidate() {        if (airport == null) {            Debug.LogError("Airport is set to null", this);        }    }    // ...}

 

Well, the simple task code is much more beautiful. Maybe it's another way?

 


Asserts (Asserts) rescue!

If you are a Unity 5.1 (or above) user, you can use the new assertion library. It is really easy to use and the internal Assert class may find all the required functions. Let's use it instead of a simple null check.

 

public class Plane : MonoBehaviour {    public Airport airport;    void OnValidate() {        Assert.IsNotNull(airport);    }    void Update() {        Assert.IsNotNull(airport);        if (Vector3.Distance(airport.transform.position, transform.position) < 1000) {            Land();        }    }    // ...}

 



As you can see, I use Assert. IsNotNull (). This function tells me that the expected value is not null. If it is null, I want to know about it.

Asserts has the following advantages:
? Simple and Easy-to-Read code
? The error message is a clean and readable assert error message.
? By default, assertion is in non-development mode (you do not need to use a Preprocessor), and the building game is stripped away.

If you want to include asserts in your build (asserts are not caused by the default exception), then all you need to do is the symbols defined in the script, you can find that UNITY_ASSERTIONS is defined in the Script Define Symbols menu of Edit-> Project Settings-> Player. The assertion will not be interrupted; the asset will only print errors and continue execution. If you want it to only act as exceptions (interrupted execution), make sure to set Assert. raiseExceptions to true from your code.

Remember, asserts may use your code anywhere (it does not have to be updated), but it is a good habit, check as much as possible the actual code that is executed before doing as much as possible. Quick failure, safe!

 

....

 

Assert is the most powerful tool to ensure code correctness (Secure Programming. When writing a program in c ++, The assert statement always occupies most of the length of the entire program.

However, after turning to unityc #, I couldn't find the assert at the beginning and endured it for a long time. Today, I had a good google and finally found it.

Introduced from unity5.1, refer to: http://answers.unity3d.com/questions/19122/assert-function.html

The following is the assert document: http://docs.unity3d.com/ScriptReference/Assertions.Assert.html

However, we recommend that you use MustExtensions instead of simply using assert, which is a more readable encapsulation of assert.

MustExtensions document: http://docs.unity3d.com/ScriptReference/Assertions.Must.MustExtensions.html

For example, if there is a variable n, I want to assert:

(1) Assertion n = 0, which can be written:

N. MustBeEqual (0, "nmust be zero! ");

Or

(N = 0). MustBeTrue ("n must be zero! ");

(2) Assertion n> 0, which can be written:

(N> 0). MustBeTrue ("n must greater than zero! ");

Before using Must, you need using UnityEngine. Assertions. Must;

Difference between assertion and Debug:

Obviously:

Unity adds and encapsulates many judgment functions for assertions!

Unity is divided into release build and debug. The former release will automatically remove assertions, but Log should be controlled by yourself!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.