unity中 StreamingAssetsPath 文件夹和 PersistentDataPath 文件夹 区别

请转 Unity StreamingAssetsPath等特殊文件夹的权限方式记录

最近在做一个在平台频繁读写的一个项目,加载音乐的时候需要用WWW加载返回的w.audioClip,而读写xml的时候则需要用IO流读写。

于是我发现。。。Android平台路径的坑可真是不小啊
首先在Unity平台先看一下Windows系统下,各个文件夹的路径:

这里我把Unity里能打印的四个自带里文件夹路径都打印出来了,而其实,我常用的只有streamingAssetsPath和persistentDataPath
streamingAssetsPath是可以跟随Unity打包存在的文件夹,WWW和IO都可以访问这个文件夹下的文件,但是这个文件夹是只读文件夹,不支持修改文件和写入等操作。
persistentDataPath是可读写的文件夹,但是这个文件夹是在APK安装成功后创建的,所以无法将文件在打包前放入此文件夹。
那么接下来我们看看Android平台的这些文件夹路径都是什么样的。

下面开始分享我的经验一、    如果用WWW去加载文件:

  • 在Windows端访问streamingAssetsPath文件夹则需要在前面加上”file:///”协议,而Android端则不用加file协议,因为Android端的streamingAssetsPath路径Unity会自动为他添加jar:file://。
  • 同样,如果是persistentDataPath文件夹,在Windows端一样需要加”file:///”协议 ,而Android端的persistentDataPath文件夹Unity则没有像streamingAssetsPath一样,添加了jar:file://,所以,我们要在此路径前自己添一下file协议(PS:Android端的file协议需要在file前添加”jar:”)。
     

二、    如果用IO流去读写文件:

 

不管是Windows端还是Android端都是不需要file协议的.

 

但是streamingAssetsPath在Android端只能支持IO Stream 或者 WWW 方式读取(AssetBundle除外)。

using(FileStream stream =  File.Open(Application.streamingAssetsPath+"fileName", FileMode.Open)) 
{ 

//处理方法   //IO Stream方式

} 

//WWW方式(注意协议与不同平台下路径的区别)

using(WWW www = new WWW( 

Application.streamingAssetsPath+"fileName")) 

{ 

yield return www; 

www.text; 

www.texture; 

} 

// AssetBundle特有的同步读取方式(注意安卓平台下的路径区别)

string assetbundlePath = 

#if UNITY_ANDROID 

Application.dataPath+"!/assets"; 

#else 

Application.streamingAssetsPath; 

#endif  

AssetBundle.LoadFromFile(assetbundlePath+"/name.unity3d"); 

 

 

Windows端直接使用streamingAssetsPath即可。

 

 

而persistentDataPath路径不管是Windows端还是Android端,都可以直接使用,不需要添加file协议,但是安卓需要设置 Write Access为External(SDCard),不然没法写入。


光看文字未免有些不爽,我自己也写了一个小Demo供大家参考。
以下是代码。

 
#define log
using System.IO;
using UnityEngine;
using System.Collections;
using System;

public enum FileType
{
    None,
    AudioCilp,
    String,
    Texture,
}
public enum FolderType
{
    None,
    StreamingAssets,
    PersistentData,
}

public class FileManager: MonoBehaviour
{
    /// <summary>
    /// 显示各个文件夹路径
    /// </summary>
    public void ShowPath()
    {
        log("dataPath: ======> " + Application.dataPath);
        log("persistentDataPath: ======> " + Application.persistentDataPath);
        log("streamingAssetsPath: ======> " + Application.streamingAssetsPath);
        log("temporaryCachePath: ======> " + Application.temporaryCachePath);
        
    }


    /// <summary>
    /// 将StreamingAssets里的文件复制到PersistentDataPath下
    /// </summary>
    public void CopyStreamingFileToPersistentDataPath(params string[] filePath)
    {
        if (Application.platform == RuntimePlatform.Android)                    //如果是Android平台
        {
            foreach(string path in filePath)
            {
                StartCoroutine(CopyFile_Android(path));
            }
        }
        else if (Application.platform == RuntimePlatform.WindowsEditor)          //如果是Windows平台
        {
            foreach (string path in filePath)
            {
                File.Copy(Application.streamingAssetsPath + "/" + path, Application.persistentDataPath + "/" + path, true);

                log("CopyMusic Success!" + "\n" + "Path: ======> " + Application.persistentDataPath + "/" + path);
            }
        }

    }

    
    /// <summary>
    /// 从StreamingAssets加载文件
    /// </summary>
    public void LoadFileByStreamingAssets(string file,FileType fileType, Action<object> Callback)
    {
        FileType m_FileType = fileType;
        FolderType m_FolderType = FolderType.StreamingAssets;

        StartCoroutine(LoadFileIEnumerator(file, Callback, m_FileType, m_FolderType));
    }



    /// <summary>
    /// 从PersistentDataPath加载文件
    /// </summary>
    public void LoadFileByPersistentDataPath(string file, FileType fileType, Action<object> Callback)
    {
        FileType m_FileType = fileType;
        FolderType m_FolderType = FolderType.PersistentData;

        StartCoroutine(LoadFileIEnumerator(file, Callback, m_FileType, m_FolderType));
    }
    
    
    //===============================================================================

    /// <summary>
    /// 加载文件
    /// </summary>
    IEnumerator LoadFileIEnumerator(string file,Action<object> Callback, FileType fileType, FolderType m_FolderType)
    {
        string filePath = "";

        switch (m_FolderType)
        {
            case FolderType.StreamingAssets:
                if (Application.platform == RuntimePlatform.Android)                    //如果是Android平台
                {
                    filePath = Application.streamingAssetsPath + "/" + file;
                }
                else if (Application.platform == RuntimePlatform.WindowsEditor)          //如果是Windows平台
                {
                    filePath = "file:///" + Application.streamingAssetsPath + "/" + file;
                }
                break;
            case FolderType.PersistentData:
                if (Application.platform == RuntimePlatform.Android)                    //如果是Android平台
                {
                    filePath = "file://" + Application.persistentDataPath + "/" + file;
                }
                else if (Application.platform == RuntimePlatform.WindowsEditor)          //如果是Windows平台
                {
                    filePath = "file:///" + Application.persistentDataPath + "/" + file;
                }
                break;
        }
        

        WWW w = new WWW(filePath);

        yield return w;


        if (w.error == null)
        {
            switch (fileType)
            {
                case FileType.AudioCilp:
                    //我使用的Unity是2017.3.0.此处 这里只 支持 .ogg 格式的 音频
                    Callback(w.GetAudioClip());
                    break;
                case FileType.String:
                    string data = System.Text.Encoding.UTF8.GetString(w.bytes);
                    Callback(data);
                    break;
                case FileType.Texture:
                    Callback(w.texture);
                    break;
                default:
                    break;
            }
            

            switch (m_FolderType)
            {

                case FolderType.StreamingAssets:
                    log("StreamingAssetsPath Load Success...");
                    break;
                case FolderType.PersistentData:
                    log("PersistentDataPath Load Success...");
                    break;
            }
            
        }
        else
        {

            log("Error : ======> " + w.error);

        }

    }
    

    /// <summary>
    /// 安卓端复制文件
    /// </summary>
    /// <param name="fileName">文件路径</param>
    /// <returns></returns>
    IEnumerator CopyFile_Android(string fileName)
    {
        WWW w = new WWW(Application.streamingAssetsPath + "/" + fileName);

        yield return w;

        if (w.error == null)
        {
            FileInfo fi = new FileInfo(Application.persistentDataPath + "/" + fileName);

            //判断文件是否存在
            if (!fi.Exists)
            {
                FileStream fs = fi.OpenWrite();

                fs.Write(w.bytes, 0, w.bytes.Length);

                fs.Flush();

                fs.Close();

                fs.Dispose();

                log("CopyTxt Success!" + "\n" + "Path: ======> " + Application.persistentDataPath + fileName);

            }

        }
        else
        {
            log("Error : ======> " + w.error);
        }

    }

    /// <summary>
    /// 向我的控制台打印内容
    /// </summary>
    /// <param name="content">内容</param>
    void log(string content)
    {
#if log
        Debug.Log(content);
#endif

    }
}


之后通过下面脚本就可以使用了 :

 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameApp : MonoBehaviour {

  
    public FileManager TextFileRead;
    
    void Awake()
    {
     
        TextFileRead = gameObject.AddComponent<FileManager>();
        TextFileRead.LoadFileByStreamingAssets("TextJson.json", FileType.String ,delegate(object o) { Debug.Log("hahahha :" + (o as string)); } );

        TextFileRead.LoadFileByStreamingAssets("JRFog.ogg", FileType.AudioCilp, delegate (object o) { PlaySound(o); });

    }

    public void PlaySound(object o)
    {
        if(o is AudioClip)
        {
            AudioSource audio =  GetComponent<AudioSource>();
            audio.clip = (o as AudioClip);
            audio.Play();
            Debug.Log("播放成功");
        }
        else
        {
            Debug.Log("无法播放的音频类型");
        }
    }


}


 

 


只是个人经验分享,如有不对的地方,还望大家指正谢谢。

 

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值