May 12, 2012

Debugging context in Unity3D

Tags: ,

A cool little feature of Unity3D scripting I recently found is using conditional compilation for debug statements. The C based languages (but not Java unfortuately) have inbuilt preprocessors that allow developers to only compile certain parts of the code if certain parameters are set (it can also do much more, including macros). Thus you could write the below and the code would only be included in the executable if DEBUG is defined.

#if DEBUG
    // do some special code
#endif

Unity3D has a similar system. Mostly the docs (available here) seem to suggest this is for specialist code for different platforms: iPhone, Web, PC, etc. Thus the defined parameters are set in advance (e.g. UNITY_IPHONE). However, there is one that is useful for debugging, UNITY_EDITOR. This will only be set if the application is running inside the Unity3D GUI. Once you build the app those lines of code will be skipped. It can be used like the below example – very handy.

#if UNITY_EDITOR
    Debug.Log("Debugging");
#endif 

According to this Unity3D forum post it is also possible to define your own project specific preprocessor parameters.


comments powered by Disqus