Version: 2019.2

PreserveAttribute

class in UnityEngine.Scripting

マニュアルに切り替える

説明

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" を持つどのような属性でも考慮します。