如何在Android或iPhone上原生访问Unity资产?

时间:2011-11-23 18:00:12

标签: android iphone unity3d assets

我需要在Unity插件项目中在Android和iPhone上本地访问文件(来自C ++或Java代码)。 Unity是否提供了访问项目资产中文件的任何方法?

2 个答案:

答案 0 :(得分:6)

  1. 我的解决方法是将文件从Application.streamingAssetsPath(在jar中,并且不能被大多数本机库访问)复制到Application.persistentDataPath(这完全没问题),然后将该路径传递给本机代码。
  2. 项目中的源文件应位于Assets \ StreamingAssets
  3. c#中用于复制文件异步的小示例代码: 将此方法添加到继承MonoBehaviour

    的脚本中
    IEnumerator CopyFileAsyncOnAndroid()
    {
        string fromPath = Application.streamingAssetsPath +"/";
        //In Android = "jar:file://" + Application.dataPath + "!/assets/" 
        string toPath =   Application.persistentDataPath +"/";
    
        string[] filesNamesToCopy = new string[] { "a.txt" ,"b.txt"};
        foreach (string fileName in filesNamesToCopy)
        {
            Debug.Log("copying from "+ fromPath + fileName +" to "+ toPath);
            WWW www1 = new WWW( fromPath +fileName);
            yield return www1;
            Debug.Log("yield done");
            File.WriteAllBytes(toPath+ fileName, www1.bytes);
            Debug.Log("file copy done");
        }
        //ADD YOUR CALL TO NATIVE CODE HERE
        //Note: 4 small files can take a second to finish copy. so do it once and
        //set a persistent flag to know you don`t need to call it again
    }
    

答案 1 :(得分:0)

在运行时访问文件仅限于目录资产/资源。可以通过Resources.Load方法(doc)访问放置在那里的所有内容,但是没有机会从文件夹外部获取内容。

在Assets / Resources文件夹中,您可以设置任意文件夹结构。我在一个iPhone项目中使用它来从预定义的文本文件中进行关卡构建,它就像一个魅力。