PreserveAttribute
Prevents byte code stripping from removing a class, method, field, or property.
阅读时间4 分钟最后更新于 15 天前
Definition
- Type: Class
- Namespace: UnityEngine.Scripting
- Assembly: UnityEngine.ScriptingModule
- Inherits from: Attribute
[AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Class|AttributeTargets.Struct|AttributeTargets.Enum|AttributeTargets.Constructor|AttributeTargets.Method|AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Event|AttributeTargets.Interface|AttributeTargets.Delegate, Inherited = false)]public class PreserveAttribute : Attribute
Remarks
When you create a build, Unity tries to strip unused code from your project, which can help keep build sizes small. However, you might want some code to not be stripped, even if it looks like it's not used. This can happen if for example you use reflection to call a method, or instantiate an object of a certain class.
You can apply the attribute to classes, methods, fields and properties. You can also use a link.xml file to tell the linker to not remove things.
[Preserve]For more details on and link.xml, refer to Managed code stripping.
[Preserve]For third party libraries that don't take on a dependency on UnityEngine.dll, they can define their own . The code stripper respects that and also considers any attribute with the exact name as a reason not to code strip, regardless of the namespace or assembly of the attribute.
PreserveAttributePreserveAttributeExamples
using UnityEngine;using System.Collections;using System.Reflection;using UnityEngine.Scripting;public class NewBehaviourScript : MonoBehaviour{ void Start() { ReflectionExample.InvokeBoinkByReflection(); }}public class ReflectionExample{ static public void InvokeBoinkByReflection() { typeof(ReflectionExample).GetMethod("Boink", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null); } // No other code directly references the Boink method, so when when stripping is enabled, // it will be removed unless the [Preserve] attribute is applied. [Preserve] static void Boink() { Debug.Log("Boink"); }}