IL2CPP runtime code checks
Configure IL2CPP's generation of C++ to enable or disable the inclusion of runtime safety features such as null reference and out of bounds checks.
Read time 3 minutesLast updated 4 days ago
You can use the C# attribute and its parameter to control which safety checks the IL2CPP compiler includes in the C++ code it generates.
[Il2CppSetOption]OptionThe attribute is not part of the standard Unity Editor and Engine public APIs but its source is shipped separately as part of your Unity installation. To use the attribute:
[Il2CppSetOption][Il2CppSetOption]- In the directory where your Unity version is installed, navigate to the directory on Windows, or the
Data\il2cppdirectory on macOS.Contents/Frameworks/il2cpp - Find the source file.
Il2CppSetOptionAttribute.cs - Copy the source file into your project's folder.
Assets
The supported options for the attribute are as follows:
Property | Description | Default |
|---|---|---|
| Null checks | It's recommended to keep this option enabled. When disabled, IL2CPP generates C++ without null checks and won't throw managed | Enabled |
| Array bounds checks | It's recommended to keep this option enabled. When disabled, IL2CPP generates C++ without array bounds checks and won't throw managed | Enabled |
| Divide by zero checks | Keep this option disabled unless you need to run divide by zero checks. When enabled, IL2CPP generates C++ that contains divide by zero checks for integer division and throws managed These checks have an impact on performance at runtime. | Disabled |
The following example shows how to use the attribute:
[Il2CppSetOption][Il2CppSetOption(Option.NullChecks, false)]public static string MethodWithNullChecksDisabled(){ var tmp = new object(); return tmp.ToString();}
You can apply to assemblies, types, methods, and properties. Unity uses the attribute from the most local scope.
[Il2CppSetOption][Il2CppSetOption(Option.NullChecks, false)]public class TypeWithNullChecksDisabled{ public static string AnyMethod() { // Unity doesn’t perform null checks in this method. var tmp = new object(); return tmp.ToString(); } [Il2CppSetOption(Option.NullChecks, true)] public static string MethodWithNullChecksEnabled() { // Unity performs null checks in this method. var tmp = new object(); return tmp.ToString(); }}public class SomeType{ [Il2CppSetOption(Option.NullChecks, false)] public string PropertyWithNullChecksDisabled { get { // Unity doesn't perform null checks here. var tmp = new object(); return tmp.ToString(); } set { // Unity doesn't perform null checks here. value.ToString(); } } public string PropertyWithNullChecksDisabledOnGetterOnly { [Il2CppSetOption(Option.NullChecks, false)] get { // Unity doesn’t perform null checks here. var tmp = new object(); return tmp.ToString(); } set { // Unity performs null checks here. value.ToString(); } }}