Version: 2021.3

PreserveAttribute

class in UnityEngine.Scripting

切换到手册

描述

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

当您创建编译版本时,Unity 将尝试从项目中剥离未使用的代码。这有利于获取小型编译版本。但有时,即使某些代码看起来未曾使用,您也不希望将其剥离。这种情况有可能会发生,如使用反射来调用一个方法或者实例化某个类的对象时。 您可以将 [Preserve] 属性应用于类、方法、字段以及属性。除了使用 PreserveAttribute 之外,您也可以使用 link.xml 文件的传统方法来告知链接器不要移除某些代码。PreserveAttribute 和 link.xml 适用于 Mono 和 IL2CPP 脚本后端。

有关[Preserve] and link.xml see 托管代码剥离的更多详细信息。

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

For 3rd party libraries that do not want to take on a dependency on UnityEngine.dll, it is also possible to define their own PreserveAttribute. The code stripper will respect that too, and it will consider any attribute with the exact name "PreserveAttribute" as a reason not to strip the thing it is applied on, regardless of the namespace or assembly of the attribute.