在Unity中加载本地插件资源

3

我该如何在本地插件中加载资源(文本文件、纹理等)?我正在尝试实现对Resources.Load()的mono调用,但我不确定如何处理此操作将返回的对象(假设它成功)。非常感谢您的帮助 :)


嗯,本地插件意味着像iOS或Android这样的平台……或者我理解错了吗? - Kay
不,你读得没错,它还包括PC和OSX :) - hatboyzero
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

Unity的最新版本可以通过http://docs.unity3d.com/Documentation/ScriptReference/Application-streamingAssetsPath.html返回路径。 - ftvs

4
我希望为这个问题提供一个关于原生端的答案。 iOS 实际上很简单 - 你可以通过以下方式在原生端获取StreamingAssets路径:
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
NSString* streamingAssetsPath = [NSString stringWithFormat:@"%@/Data/Raw/", bundlePath];

安卓

我不喜欢在安卓上使用流媒体资产,因为它需要复制所有文件,这很麻烦。更清晰的做法是在插件目录中创建文档定义的目录结构。

例如,在您的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);

其余的处理方式由您决定!希望这有所帮助 :)


你的意思是将Unity项目导出为Android Studio项目,并在Java代码中读取它们吗? - flankechen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接