Unity在persistentDataPath创建初始数据

该博客介绍了如何在Unity游戏中处理持久化数据路径。当首次运行游戏时,如果persistentDataPath中没有数据,程序会从StreamingAssetsPath复制数据到persistentDataPath。这样,即使更换电脑,也能确保初始数据的可用性。文章提供了详细的代码实现,包括文件夹创建、文件移动等操作。

有时候我们需要在第一次运行游戏的时候加载persistentDataPath中的一些数据,但是这里面的数据不会被Unity打包,如果我们换一台电脑,这些数据就没了,解决方法就是将初始数据保存在项目文件夹中,在第一次运行的时候将这些数据放在persistentDataPath就可以啦。

 		void Start()
        {
            string destPath = Application.persistentDataPath;
            //判断数据文件夹是否存在,不存在则为第一次运行
            if(!Directory.Exists(destPath))
			{
                try
                {
                    Directory.CreateDirectory(destPath);//创建数据文件夹
                }
                catch (Exception ex)
                {
                    throw new Exception("创建数据文件夹失败:" + ex.Message);
                }

                MoveFolder(Application.streamingAssetsPath, destPath);
            }
        }
       /// <summary>
        /// 移动文件夹中的所有文件夹与文件到另一个文件夹 //转载请注明来自 http://www.uzhanbao.com
        /// </summary>
        /// <param name="sourcePath">源文件夹</param>
        /// <param name="destPath">目标文件夹</param>
        public static void MoveFolder (string sourcePath , string destPath)
        {
            if (Directory.Exists(sourcePath))
            {
				if (!Directory.Exists(destPath))
				{
					//目标目录不存在则创建
					try
					{
						Directory.CreateDirectory(destPath);
					}
					catch (Exception ex)
					{
						throw new Exception("创建目标目录失败:" + ex.Message);
					}
				}
				//获得源文件下所有文件
				List<string> files = new List<string>(Directory.GetFiles(sourcePath));
                files.ForEach(c =>
                {
                    string destFile = Path.Combine(new string[] { destPath , Path.GetFileName(c) });
                    //覆盖模式
                    if (File.Exists(destFile))
                    {
                        File.Delete(destFile);
                    }
                    File.Copy(c , destFile);
                });
                //获得源文件下所有目录文件
                List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));

                folders.ForEach(c =>
                {
                    string destDir = Path.Combine(new string[] { destPath , Path.GetFileName(c) });
                    //Directory.Move必须要在同一个根目录下移动才有效,不能在不同卷中移动。
                    //Directory.Move(c, destDir);

                    //采用递归的方法实现
                    MoveFolder(c , destDir);
                });
            }
            else
            {
                throw new DirectoryNotFoundException("源目录不存在!");
            }
        }

转载自:https://blog.youkuaiyun.com/szsbell/article/details/51800424

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值