unity 初始化数据存储问题

在用unity进行开发的时初始化的数据和中间实时生成的数据存储不同,初始化文件数据建议安放在asset-StreamingAssets文件下,需要时读取取来。运行时所需的实时文件或数据持久化的xml文件则放在Application.persistentDataPath中。就项目开发中出现的问题以及解决方法做以下说明。

1)android应用开发时,从打包文件中读取数据并存储到Application.persistentDataPath中。

   IEnumerator CopyXmlConfig()
    {
        //string strDestDir =Path.Combine(TransitData.appPersitPath, "iniXmlFile");
        string strDestDir = TransitData.appPersitPath;
        if (!Directory.Exists(strDestDir))
        {
            Directory.CreateDirectory(strDestDir);
        }

        yield return StartCoroutine(CopyAssetFileToPersistentPath("MenuData.xml", strDestDir));
        yield return StartCoroutine(CopyAssetFileToPersistentPath("OrderMenuData.xml", strDestDir));
    }
    IEnumerator CopyAssetFileToPersistentPath(string assetFile,string destFile)
    {
        string src = (new System.Uri(Path.Combine(Application.streamingAssetsPath ,assetFile))).AbsoluteUri;
        //string src = "file:///" + Application.dataPath + "/" + assetFile;

        using (WWW www = new WWW(src))
        {
            yield return www;

            if (!string.IsNullOrEmpty(www.error))
            {
                yield break;
            }

            string dest =Path.Combine(destFile, assetFile);

            using (BinaryWriter sw = new BinaryWriter(File.Open(dest, FileMode.Create, FileAccess.ReadWrite)))
            {               
                sw.Write(www.bytes);
                sw.Flush();
                sw.Close();
            }
        }
    }
    private void Awake()
    {
        StartCoroutine(CopyXmlConfig());
    }

2)此问题是关于Application.persistentDataPath路径问题

这是一个坑,由于涉及到android平台是否内置内存卡等问题,调用相关路径时并不能如愿,此问题在一些山寨pad中尤为明显。在pc端可以放心使用此路径,在android端可采用如下路径

    public static string appPersitPath
    {
        get
        {
        #if UNITY_EDITOR_WIN

            return @"C:UsersDDAppDataLocalLow1111_unity";// Application.persistentDataPath;

        #endif

        #if UNITY_ANDROID

            using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            {
                using (AndroidJavaObject currentActivity = jc.GetStatic<AndroidJavaObject>("currentActivity"))
                {
                    path = currentActivity.Call<AndroidJavaObject>("getFilesDir").Call<string>("getCanonicalPath");
                }
            }
            return path;

        #endif
        }
    }

ps:对于unity预处理命令可以参考https://docs.unity3d.com/Manual/PlatformDependentCompilation.html中的介绍

原文地址:https://www.cnblogs.com/llstart-new0201/p/7263474.html