Unity3d 打包检查引用丢失脚本

新建 BuildAPKCheck 脚本, 放在项目Editor (防止打包安卓工程的时候报错) 路径下即可:

using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

public class BuildAPKCheck : MonoBehaviour, IPreprocessBuildWithReport
{
    public int callbackOrder { get; }

    public void OnPreprocessBuild(BuildReport report)
    {
        // clearConsole();
        findMissingReferencesInScene();
    }
    
    private void findMissingReferencesInScene()
    {
        List<Component> components = new List<Component>();
        
        // TODO: ADD NEED CHECK COMPONENT
        UIManager uiManager = GameObject.FindObjectOfType<UIManager>();
        FightUIController fightUIController = GameObject.FindObjectOfType<FightUIController>();
        HomeController homeController = GameObject.FindObjectOfType<HomeController>();

        if (uiManager) components.Add(uiManager);
        if (fightUIController) components.Add(fightUIController);
        if (homeController) components.Add(homeController);

        bool hasError = false;
        for (var j = 0; j < components.Count; j++)
        {
            var c = components[j];

            using (var so = new SerializedObject(c))
            {
                using (var sp = so.GetIterator())
                {
                    while (sp.NextVisible(true))
                    {
                        if (sp.propertyType == SerializedPropertyType.ObjectReference)
                        {                          
                            if (sp.objectReferenceValue == null)
                            {
                                hasError = true;
                                Debug.LogError($"Game场景中, {c.name}的字段 {sp.name} 丢失引用: {sp.propertyType}", c);
                            }
                        }
                    }
                }
            }
        }

        if (hasError)
        {
            throw new BuildFailedException("打包失败!");
        }
    }

    private static void clearConsole()
    {
        var logEntries = Type.GetType("UnityEditor.LogEntries, UnityEditor.dll");
        if (logEntries == null) return;

        var clearMethod = logEntries.GetMethod("Clear",
            BindingFlags.Static | BindingFlags.Public);
        if (clearMethod == null) return;

        clearMethod.Invoke(null, null);
    }
}

你可能感兴趣的:(unity,unity)