Version: 2021.1

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

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

Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961