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",则代码剥离器不会剥离应用了此类属性的代码,无论此类属性的命名空间或程序集如何。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.