Unity 打包_打包完成后的回调

 

unity Build 导出可执行文件后,很多时候需要把配置文件或者相关的文件拷贝到与导出包体同级的目录,如果每次多手动去拷贝,未免过于麻烦和繁琐,这个时候我们希望打包完成后通过代码自动拷贝相关文件到导出路径。为此,我们就必须知道什么打包完成,和导出包体的路径,Unity给我们提供了一个特性:

[PostProcessBuild(1)] 

它的功能是打包完成后的回调

  /// 
    /// Build完成后的回调
    /// 
    /// 打包的目标平台
    /// 包体的完整路径
    [PostProcessBuild(1)]
    public static void AfterBuild(BuildTarget target, string pathToBuiltProject)
    {
        Debug.Log("Build Success  输出平台: " + target + "  输出路径: " + pathToBuiltProject);

       //打开文件或文件夹
       System.Diagnostics.Process.Start(pathToBuiltProject);

        int index = pathToBuiltProject.LastIndexOf("/");

        Debug.Log("导出包体的目录 :"+pathToBuiltProject.Substring(0, index));
    }

 

打包完成后,拷贝相关文件夹到与包体同级的目录

[PostProcessBuild(1)]
	public static void AfterBuild(BuildTarget target, string pathToBuiltProject)
	{
		Debug.Log("Build Success  输出平台: " + target + "  输出路径: " + pathToBuiltProject);
		string buildPath = pathToBuiltProject.Substring(0, pathToBuiltProject.LastIndexOf("/"));

		Debug.Log(buildPath);

		string configName = "config.ini";
        string allConfigDirName = "SceneModeInFo";

        DirectoryInfo appDir = new DirectoryInfo(Application.dataPath);
		File.Copy(Path.Combine(appDir.Parent.FullName,configName), Path.Combine(buildPath, configName), true);


        string copyDir = Path.Combine(appDir.Parent.FullName, allConfigDirName);
        string tgtDir = Path.Combine(buildPath, allConfigDirName);

        CopyDirectory(copyDir, tgtDir);

		Debug.Log("打包完成!");

	}


	/// 
	/// 复制文件夹
	/// 
	/// 
	/// 
	public static void CopyDirectory(string srcDir, string tgtDir)
	{
		DirectoryInfo source = new DirectoryInfo(srcDir);
		DirectoryInfo target = new DirectoryInfo(tgtDir);

		if (target.FullName.StartsWith(source.FullName, StringComparison.CurrentCultureIgnoreCase))
		{
			throw new Exception("父目录不能拷贝到子目录!");
		}
		if (!source.Exists)
		{
			return;
		}
		if (!target.Exists)
		{
			target.Create();
		}
		FileInfo[] files = source.GetFiles();
		for (int i = 0; i < files.Length; i++)
		{
			File.Copy(files[i].FullName, Path.Combine(target.FullName, files[i].Name), true);
		}
		DirectoryInfo[] dirs = source.GetDirectories();
		for (int j = 0; j < dirs.Length; j++)
		{
			CopyDirectory(dirs[j].FullName, Path.Combine(target.FullName, dirs[j].Name));
		}
	}

 

 

你可能感兴趣的:(Unity,Editor)