您的位置:首页 > 移动开发 > Unity3D

Unity3d发布Android版通过WWW加载本地AssetBundle资源

2015-05-06 17:42 477 查看
不久之前买了小米平板,就想着用Unity3d做个小游戏放在平板上玩玩,匆匆做了个资源加载界面就发布apk到平板上,结果提示资源加载失败,找不到资源文件。在网上找了半天资料都没解决问题,最后发现自己犯了个最愚蠢的问题,就是StreamingAssets文件夹名称有问题,我写成了StreamingAsset,真是被自己给坑到了。



下面总结下Unity3d发布Android版通过WWW加载本地AssetBundle资源的注意事项:

(1)一定要将需要加载的AssetBundle资源文件放在StreamingAssets目录下,因为Android只能加载StreamingAssets中的内容。

(2)打包AssetBundle资源包时需要打包平台为BuildTarget.Android

using UnityEngine;
using System.Collections;
using UnityEditor;//必须引用此类
public class ExportAssetBundles : MonoBehaviour
{
/// <summary>
/// 将所选择的的物体和物体有依赖关系的对象一起打包
/// </summary>
[MenuItem("Assets/Build AssetBundle From Selection - Track dependencies")]
static void ExportResource()
{
// Bring up save panel
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
if (path.Length != 0)
{
// Build the resource file from the active selection.
Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies |
BuildAssetBundleOptions.CompleteAssets, BuildTarget.Android);
Selection.objects = selection;
}
}
/// <summary>
/// 只打包选择的物体
/// </summary>
[MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]
static void ExportResourceNoTrack()
{
// Bring up save panel
string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
if (path.Length != 0)
{
// Build the resource file from the active selection.
BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
}
}
}
(3)注意加载文件的路径,判断运行平台请用Application.platform == RuntimePlatform.Android这种方式。

Windows :  path = = Application.dataPath + "/StreamingAssets";

On iOS: path = Application.dataPath + "/Raw";

Android:path = "jar:file://" + Application.dataPath + "!/assets/";

Application.platform == RuntimePlatform.Android
下面是我的代码:
using System;
using System.Collections;
using UnityEngine;

namespace HKScripts
{
class HKLoadResource : MonoBehaviour
{
public static float progress = 0;

private WWW www = null;
void Awake()
{
StartCoroutine("loadEnvironment");
}

void Update()
{
if (www!=null)
{
progress = www.progress;
}
}

IEnumerator loadEnvironment()
{
string url = "";
if (Application.platform == RuntimePlatform.Android)
url = "jar:file://" + Application.dataPath + "!/assets/Environment.unity3d";
else
url = "file:///" + Application.dataPath + "/../Environment.unity3d";
Debug.LogError(url);
www = new WWW(url);
yield return www;
if (www.error != null)
{
GameObject.FindGameObjectWithTag("TipLabel").GetComponent<UILabel>().text = "路径:" + url + "错误:" + www.error;
Debug.LogError(www.error);
yield return null;
}

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息