PreserveAttribute

class in UnityEngine.Scripting

Switch to Manual

Description

PreserveAttribute 可防止字节码剥离移除类、方法、字段或属性。

When you create a build, Unity will try to strip unused code from your project. This is great to get small builds. However, sometimes you want some code to not be stripped, even if it looks like it is not used. This can happen for instance if you use reflection to call a method, or instantiate an object of a certain class. You can apply the [Preserve] attribute to classes, methods, fields and properties. In addition to using PreserveAttribute, you can also use the traditional method of a link.xml file to tell the linker to not remove things. PreserveAttribute and link.xml work for both the Mono and IL2CPP scripting backends.

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"); } }

对于不希望依赖 UnityEngine.dll 的第三方库来说,也可以定义它们自己的 PreserveAttribute。代码剥离器也会遵守这一规则;此外,如果有任何属性具有确切的名称"PreserveAtribute",则代码剥离器不会剥离应用了此类属性的代码,无论此类属性的命名空间或程序集如何。