u3d+android+不必要的脚本,说说用unity实现动态加载模型的步骤,以及脚本(unity+easyAR),一个动态加载问题坑了我3周,给后来者借鉴...

首先申明我实现的是我用unity发布的安卓工程,集成到AndroidStudio里面的。我这边是安卓原生传递一个字符串给我,我接收这个字符串,判断该字符串,然后从服务器里面加载不同的模型。

1.在unity里面创建打包模型的工具。俗称的AB打包。在unity里面的Project下创建一个特殊文件夹Editor,在Editor下创建C#脚本,如下

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEditor;

public class CreateAssetBundle

{

[MenuItem("Bulid/Bulid AssetBundles")]

public static void  BuildCreateAssetBundle()

{

#if UNITY_ANDROID    //宏定义

BuildPipeline.BuildAssetBundles(Application .streamingAssetsPath ,

BuildAssetBundleOptions.UncompressedAssetBundle,

BuildTarget.Android);

Debug.Log(Application.streamingAssetsPath);

AssetDatabase.Refresh();

#elif UNITY_IPHONE

BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath,

BuildAssetBundleOptions.UncompressedAssetBundle,

BuildTarget.iOS);

AssetDatabase.Refresh();

#elif UNITY_STANDALONE_WIN || UNITY_EDITOR

BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath,

BuildAssetBundleOptions.UncompressedAssetBundle,

BuildTarget.StandaloneWindows);

AssetDatabase.Refresh();

#endif

}

}

脚本保存好之后,在unity最上方的菜单栏里面会出现一个Bulid ,点击下面的选项就可以在StreamingAssets(首先你的在Project下建立这个文件夹)文件下出现打包的预设体了。(预设体的名字别忘设置了,不然打包不出文件来)。

2.把打的AB包(.assetbundle文件)先自己在本地测试一下,成功了之后让相应的同事传到服务器上。

3.开始实现本地动态加载。先说说自己本地测试你的.assetbundle文件可以加载出来不(如我的叫cube.assetbundle)下面是本地加载的脚本

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

///

/// 资源加载方式一

///

public class Load : MonoBehaviour

{

private string pathUrl;

private void Start()

{

print("加载了");

pathUrl =

#if UNITY_ANDROID

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

#elif UNITY_IPHONE

Application.dataPath + "/Raw/";

#elif UNITY_STANDALONE_WIN || UNITY_EDITOR

"file://" + Application.streamingAssetsPath;

#endif

print(Application.streamingAssetsPath);

}

///

/// 加载ab文件

///

/// ab打包文件名

/// ab文件名称

///

private IEnumerator LoadAsset(string assetBundle, string resName)

{

string mUrl = pathUrl + assetBundle;//本地加载

//string mUrl = pathUrl ;//www加载

WWW www = new WWW(mUrl);

yield return www;      //等待www加载完成

if (!string.IsNullOrEmpty(www.error))

Debug.Log(www.error);

else

{

Object obj = www.assetBundle.LoadAsset(resName);

yield return Instantiate(obj);

www.assetBundle.Unload(false);//卸载bundle中的对象

//false 只卸载用过的  true是卸载全部

}

www.Dispose();

}

public void Show()

{

StartCoroutine(LoadAsset("cube.assetbundle", "Cube"));

}

}

4.服务器的动态加载,脚本如下

private string url;//服务器的网址

public void Show()

{

url = @"服务器地址";

StartCoroutine(wwwLoad("Cube"));//开启协程

}

private IEnumerator wwwLoad(string name)

{

WWW www = new WWW(url);//www加载

yield return www;

if (www.isDone && www.error == null)//判断加载是否出错

{

AssetBundle asset = www.assetBundle;

Object obj = www.assetBundle.LoadAsset(name);

GameObject dice = Instantiate(obj) as GameObject;//实例化模型

dice.transform.position = new Vector3(0, 0, 15);//初始化模型的位置

}

}

5.打包apk测试