One issue I think would be important to highlight in the build documentation is the pitfall of building for a build target that is not the active build target.
This can work fine for many cases but can then break when build-related code is using platform-specific conditional compilation. Some editor code will not run or code for the wrong platform will run, leading to features silently breaking or compile errors.
There are Unity packages that have this issue, so I basically consider it a requirement for the active build target and the target of BuildPipeline.BuildPlayer() to match.
All the examples should either check the active build target and fail, if the active and desired targets don’t match, or switch the active build target before starting the build. The latter is pretty complicated, as it involves a domain reload, so an example of how to do that would be great as well.
Background:
When calling BuildPipeline.BuildPlayer(), the editor code cannot be reloaded, as it’s executing the build. If some editor code is using #if UNITY_XYZ platform-specific conditional compilation, which code is active and will run during the build depends on the active build target and not the target passed to BuildPlayer. If the build is done for a different target than the active one, the platform-dependent conditionally compiled code can either run for the wrong platform or be incorrectly skipped.
e.g.
using UnityEditor;
#if UNITY_IOS
// iOS-specific build code here
#elif UNITY_ANDROID
// Android-specific build code here
#endif
// Assuming this prints "BuildTarget.Android", meaning the Android code
// block above is active and the iOS block skipped.
Debug.Log(EditorUserBuildSettings.activeBuildTarget);
// Doing an iOS build in this case will not change this, the iOS block
// will be skipped and the Android block executed instead.
BuildPipeline.BuildPlayer(null, "Build/iOS", BuildTarget.iOS, BuildOptions.None);
The two options are to either never use target-dependent conditional compilation for editor code or to always switch the active build target before a build. Since you can’t control third-party code and even Unity’s own code breaks the first rule, the only viable option is to always do the active build target switch.
(Note that if you use the editor UI, Unity already forces you to switch the active build target first. This problem only applies to script builds.)