【Unity】自动复制海康威视SDK到打包目录

海康SDK在Unity使用的坑

由于项目需要使用海康的摄像头,所以需要使用海康的SDK。在unity工程内使用没有什么问题,但是打包出来以后就有一个比较坑的问题,那就是unity会自动把DLL都打包进
{项目名}_Data/Plugins/x86_64文件夹下。但是海康的api的路径是去{项目名}_Data/Plugins/x86_64/HCNetSDKCom文件夹下面找DLL。导致untiy打包后的运行的时候,获取DLL会因为路径问题失效,获取不到摄像头画面。简单一点的办法就是手动把HCNetSDKCom文件夹复制到x86_64文件夹下。但是这样就有个问题,如果某一次打包完以后忘记复制了,就会导致获取不到摄像头。所以我打算在打包的时候,自动把这个文件复制进去。

话不多说,直接上代码

using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using System.IO;
using UnityEngine;
using UnityEditor.Callbacks;

public class CopyFilesBeforeBuild : MonoBehaviour
{
    public int callbackOrder => 0;

    [PostProcessBuild]
    public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
    {
        //     if (buildTarget != BuildTarget.StandaloneWindows || buildTarget != BuildTarget.StandaloneWindows64)
        //         return;
        string sourcePath = Path.Combine(Application.dataPath, "Plugins/DLL/HIKSDK/HCNetSDKCom");
        string buildPath = Path.GetDirectoryName(path);
        string targetPath = Path.Combine(buildPath + "/" + Application.productName + "_Data", "Plugins/x86_64/HCNetSDKCom");

        Debug.Log(buildPath + " " + Directory.Exists(buildPath));
        Debug.Log(sourcePath + " " + Directory.Exists(sourcePath));
        Debug.Log(targetPath + " " + Directory.Exists(targetPath));
        // 确保目标目录的父路径存在
        Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
        // 创建目标目录本身
        Directory.CreateDirectory(targetPath);

        // 清空目标目录(如果存在)
        if (Directory.Exists(targetPath))
            Directory.Delete(targetPath, true);

        // 重新创建目标目录结构
        CopyDirectory(sourcePath, targetPath);

        AssetDatabase.Refresh();
    }

    private static void CopyDirectory(string source, string destination)
    {
        // 确保目标根目录存在
        Directory.CreateDirectory(destination);

        // 复制所有子目录
        foreach (string dirPath in Directory.GetDirectories(source, "*", SearchOption.AllDirectories))
            Directory.CreateDirectory(dirPath.Replace(source, destination));

        // 复制所有文件
        foreach (string filePath in Directory.GetFiles(source, "*.*", SearchOption.AllDirectories))
            File.Copy(filePath, filePath.Replace(source, destination), true);
    }
}

可以通过修改sourcePath来改变你想要复制的文件夹,通过修改targetPath来改变粘贴的路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值