What is the difference between Assembly Definitions and namespaces in Unity?
Is writing your own namespaces mean you manually add AsmDefs in code?
Is code compile time faster in one or the other, or all the same?
CodePudding user response:
Apples and oranges.
Namespaces allow you to partition code to avoid name collision. You can have multiple per assembly.
Assembly Definitions (ASMDEFs) is a purely Unity creation and simply a means to speed up compilation time. They are best thought of as the equivalent to a project file in Visual Studio in the respect of speeding compilation time. Rather than recompiling all your code, only the ASMDEF whose files were modified are recompiled whilst any follow-on ASMDEFs or non-ASMDEF code are simply “re-linked” (if applicable).
NOTE: Don’t make the mistake of thinking ASMDEFs only benefit the Unity build operation (the thing that takes 10 minutes ). They don’t. They are mainly for decreasing the delays experienced in the Editor where you are waiting to hit the Play button.
Since the output of an ASMDEF is an assembly, naturally whatever you can do in c# code also applies such as confining the code to one or more namespaces.
With regards to compilation times, it doesn’t take much to push Unity over the edge whereby delays of minutes or more are not unheard of. This always surprises new Unity users even those experienced with VS. Unity takes considerable more time to compile the same amount of code compared to VS however there is a subtle explanation as to why. Once you understand the mechanics you realise that comparing compilation times is also apples and oranges.
The reason is that, by default, ASMDEFs are disabled for user code and when Unity decides to compile your code, it does so for all platforms including x86, x64, Editor etc irrespective of your OS bitness or whether you intend to click that Play button. This also applies to any 3rd party code you have.
For this reason, even if you don’t intend to use ASMDEFs in your own code, create a child folder for all the Standard Unity Assets and 3rd party code and create a corresponding ASMDEF for it. Don’t forget to limit the ASMDEF to just the platforms you need for the maximum benefit in speedy compilation.