Conditional compilation
Sometimes, there's a need for parts of the code to be present only in specific builds. For example, you might want cheat codes to be present only in debug builds so you can test your game quickly, but have them removed in release builds, so players can't use them.
One of the common ways to handle that is to use conditional compilation which can be achieved with scripting symbols in Unity. The cheat codes example from above could could look as follows:
public class CheatManager : MonoBehaviour
{
#if DEVELOPMENT_BUILD
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
ActivateCheats();
}
}
void ActivateCheats()
{
Debug.Log("Cheats Activated!");
// ... cheat functionality
}
#endif
}
The same need of conditionally compiling out functionality can arise with networked entities. We can synchronize additional data for troubleshooting or provide some cheat commands, all of which should be removed in release builds.
To solve this, coherence provides a BakeCondition
attribute which can be applied to a networked component. The baked code for that component will be compiled only if the condition from the attribute is met:
[RequireComponent(typeof(CoherenceSync))]
[BakeConditional("DEVELOPMENT_BUILD")]
public class CheatManager : MonoBehaviour
{
[Sync]
public bool CheatsEnabled;
[Command]
public void Cheat_Teleport(Vector3 position) { /* ... */ }
}
In the example above, the CheatsEnabled
variable and Cheat_Teleport
command will be networked only if the DEVELOPMENT_BUILD symbol is present (it is automatically added by Unity when Development Build is selected in the build profile).
Last updated
Was this helpful?