3

如何从本机插件中加载资源(文本文件、纹理等)?我正在尝试实现 Resources.Load() 的单声道调用,但我不确定如何处理将从该操作返回的对象(假设它成功)。任何帮助将不胜感激 :)。

4

2 回答 2

8

Unity 支持的插件直接从本机文件系统加载资源的方法是将这些资源放入项目中名为“StreamingAssets”的文件夹中。安装基于 Unity 的应用程序后,此文件夹的内容将复制到本机文件系统(Android 除外,请参见下文)。本机端此文件夹的路径因平台而异。

在 Unity v4.x 及更高版本中,此路径可用作Application.streamingAssetsPath;

请注意,在 Android 上,您放置在 StreamingAssets 中的文件会打包到 .jar 文件中,尽管可以通过解压缩 .jar 文件来访问它们。

在 Unity v3.x 中,您必须自己手动构建路径,如下所示:

  • 除 iOS 和 Android 外的所有平台:Application.dataPath + "/StreamingAssets"
  • IOS:Application.dataPath + "/Raw"
  • Android:.jar 的路径是:"jar:file://" + Application.dataPath + "!/assets/"

这是我用来处理这个问题的一个片段:

if (Application.platform == RuntimePlatform.IPhonePlayer) dir = Application.dataPath + "/Raw/";
else if (Application.platform == RuntimePlatform.Android) {
    // On Android, we need to unpack the StreamingAssets from the .jar file in which
    // they're archived into the native file system.
    // Set "filesNeeded" to a list of files you want unpacked.
    dir = Application.temporaryCachePath + "/";
    foreach (string basename in filesNeeded) {
        if (!File.Exists(dir + basename)) {
            WWW unpackerWWW = new WWW("jar:file://" + Application.dataPath + "!/assets/" + basename);
            while (!unpackerWWW.isDone) { } // This will block in the webplayer.
            if (!string.IsNullOrEmpty(unpackerWWW.error)) {
                Debug.Log("Error unpacking 'jar:file://" + Application.dataPath + "!/assets/" + basename + "'");
                dir = "";
                break;
            }
            File.WriteAllBytes(dir + basename, unpackerWWW.bytes); // 64MB limit on File.WriteAllBytes.
        }
    }
}
else dir = Application.dataPath + "/StreamingAssets/";

请注意,在 Android 上,Android 2.2 及更早版本无法直接解压缩大型 .jar(通常大于 1 MB),因此您需要将其作为边缘情况处理。

参考资料:http ://unity3d.com/support/documentation/Manual/StreamingAssets.html ,以及http://answers.unity3d.com/questions/126578/how-do-i-get-into-my-streamingassets-folder -from-t.htmlhttp://answers.unity3d.com/questions/176129/accessing-game-files-in-xcode-project.html

于 2012-06-14T07:22:07.743 回答
4

我想就事物的本机方面提供这个问题的答案。

iOS

这真的很简单——你可以像这样进入本机端的 StreamingAssets 路径:

NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
NSString* streamingAssetsPath = [NSString stringWithFormat:@"%@/Data/Raw/", bundlePath];

安卓

我不喜欢在 Android 上使用流媒体资产,复制所有有关 IMO 的文件是一个混乱的解决方案。一种更简洁的方法是在插件目录中创建文档中定义的目录结构。

因此,例如,图像可以在您的 Unity 项目中像这样定位:

Assets/Plugins/Android/res/drawable/image.png

然后,在 Android 端,您可以像这样访问它的资源 ID:

Context context = (Context)UnityPlayer.currentActivity;
String packageName = context.getPackageName();
int imageResourceId = context.getResources().getIdentifier("image", "drawable", packageName);

由您决定如何从那里处理其他所有事情!希望这可以帮助 :)

于 2014-08-07T10:20:24.227 回答