文档

Unity Engine

Unity Engine

使用 C# 代码启用优化设置

Use a C# script to enable some optimization settings.
阅读时间2 分钟最后更新于 1 个月前

您可以使用代码启用优化 Web 构建中建议的一些优化。如果使用代码来配置这些设置,可以节省手动单独设置每个设置的时间。
注意:此脚本仅在 Unity 编辑器中有效,在构建中无效。

创建 C# 脚本来优化 Web 构建

要使用代码在 Unity 项目设置中同时启用大多数优化,请执行以下操作:
  1. 如果还没有
    Assets/Editor
    文件夹,请创建一个文件夹。
  2. 在
    Editor
    文件夹中创建一个空的 C# 脚本。
  3. 将以下代码复制粘贴到该脚本中:
    using UnityEditor;using UnityEditor.Build;using UnityEngine;public class WebOptimizer{ [MenuItem("Example/Optimize")] public static void Optimize() { var namedBuildTarget = NamedBuildTarget.WebGL; var buildOptions = BuildOptions.CompressWithLz4HC; // Set IL2CPP code generation to Optimize Size PlayerSettings.SetIl2CppCodeGeneration(namedBuildTarget, Il2CppCodeGeneration.OptimizeSize); // Set the Managed Stripping Level to High PlayerSettings.SetManagedStrippingLevel(namedBuildTarget, ManagedStrippingLevel.High); // Strip unused mesh components PlayerSettings.stripUnusedMeshComponents = true; // Enable data caching PlayerSettings.WebGL.dataCaching = true; // Set the compression format to Brotli PlayerSettings.WebGL.compressionFormat = WebGLCompressionFormat.Brotli; // Deactivate exceptions PlayerSettings.WebGL.exceptionSupport = WebGLExceptionSupport.None; // Deactivate debug symbols PlayerSettings.WebGL.debugSymbolMode = WebGLDebugSymbolMode.Off; //Enable WebAssembly 2023 features PlayerSettings.WebGL.wasm2023 = true; // Set Platform Settings to optimize for disk size (LTO) UnityEditor.WebGL.UserBuildSettings.codeOptimization = UnityEditor.WebGL.WasmCodeOptimization.DiskSizeLTO; }}
  4. 更改脚本以适应您的项目。
  5. 从工具栏中选择示例 (Example) > 优化 (Optimize) 以运行脚本。设置将更新。
要更改资源导入覆盖 (Asset Import Overrides) 的设置,请参阅构建配置文件参考。

其他资源