The use of Unity assertions in defensive programming

Assertions are used to check for illegal conditions rather than error conditions, that is, illegal conditions that should never occur when the program is working properly, to help developers quickly locate problems. Exception handling is used to deal with abnormal situations in the program, enhance the robustness and fault tolerance of the program, reduce the behavior that is not good for users in the use of the program, and prevent (usually unnecessary) users from knowing what errors have occurred.


Usually in the Unity development process, there are often a bunch of external parameters that need to be configured, but sometimes you forget to configure some parameters, and an error will be reported at this time. A slightly better approach is to write in code

if(xxx == Null)

{

Debug.Log("xxxxxx");

}

Then pass the parameters into it, and then run it, and no error will be reported. But if you need to judge a lot of content, you need to write a lot of if judgments. This is very inefficient. Is there a way to check whether the parameters are fully configured without running it?


The answer is yes, use  OnValidate(). Then use the Assert class that comes with Unity to avoid writing a lot of if in the code. There are also many useful APIs in Assert.

After writing the code in the picture above. You can see that the console will report an error when it is not running. This is very friendly to planners.

Using assertions can greatly improve security and stability. Quickly locate when something goes wrong. It also saves you the trouble of writing a lot of Debug. The key is to delete it after writing Debug. Because a lot of Debug is very GC consumption. The program should use as little string-related things as possible.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691885&siteId=291194637