Stripping - FrankNine/franknine.github.io GitHub Wiki

如果程式在 Editor 或是 Mono Build 沒有問題,出 IL2CPP 卻有問題,尤其是在 Deserialization 突然出錯,很有可能是 IL2CPP 的 Managed code stripping 機制把有實際用到的類別剔除了。

當 ProjectSettings Managed Stripping Level 設置在 Medium 以上,只在泛型宣告出現沒有 new 使用的類別,例如從 Json deserialize:

namespace GameCode
{
    public class DTO
    {
        public int Value;

        public void Method() { }
    }

    internal class Test
    {
        private void Start()
        {
            var dto = Newtonsoft.Json.JsonConvert.DeserializeObject<DTO>("{\"Value\" : 5}");
            UnityEngine.Debug.Log(dto.Value);
        }
    }
}

會收到以下錯誤訊息:

Unable to find a constructor to use for type DTO. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.

可以添加 Preserve 屬性解決 Annotate roots using the Preserve attribute

namespace GameCode
{
    [assembly: Preserve]
    public class DTO
    {
        public int Value;

        [assembly: Preserve]
        public void Method() { }
    }

    internal class Test
    {
        private void Start()
        {
            var dto = Newtonsoft.Json.JsonConvert.DeserializeObject<DTO>("{\"Value\" : 5}");
            UnityEngine.Debug.Log(dto.Value);
        }
    }
}

或是使用 link.xml

<linker>
  <assembly fullname="Assembly-CSharp" ignoreIfMissing="1">
    <type fullname="GameCode.*" preserve="all"/>
  </assembly>
</linker>

Assembly fullname 會受到 Asmdef 影響,可以在 .cs 的 Unity Inspector 裡看到:

泰文的 DateTime.ToString 可能出錯也和 Striping 有關記錄在語系問題

UPM

⚠️ **GitHub.com Fallback** ⚠️