unity 动态加载模型分两步,服务器端动态生成,客户端加载生成后的模型。
1 生成可以动态加载的模型
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class AesstBundleTest : MonoBehaviour
{
[MenuItem("Custom Bundle/Create Bundel Main")]
public static void creatBundleMain()
{
IPEndPoint udpPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6000);
UdpClient udpClient = new UdpClient(udpPoint);
while (true)
{
IPEndPoint senderPoint = new IPEndPoint(IPAddress.Any, 0);
udpClient.Receive(ref senderPoint);
byte[] sendData = Encoding.Default.GetBytes("begin");
udpClient.Send(sendData, sendData.Length, senderPoint);
Object[] os = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
print(os.Length);
bool isExist = Directory.Exists(Application.dataPath + "/StreamingAssets");
if (!isExist)
{
Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");
}
foreach (Object o in os)
{
string sourcePath = AssetDatabase.GetAssetPath(o);
string targetPath = Application.dataPath + "/StreamingAssets/" + o.name + ".assetbundle";
if (BuildPipeline.BuildAssetBundle(o, null, targetPath, BuildAssetBundleOptions.CollectDependencies, BuildTarget.StandaloneWindows64))
{
print("create bundle cuccess!");
}
else
{
print("failure happen");
}
AssetDatabase.Refresh();
}
sendData = Encoding.Default.GetBytes("end");
udpClient.Send(sendData, sendData.Length, senderPoint);
}
udpClient.Close();
}
}
2 动态调用生成的模型
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoadBundleTest : MonoBehaviour {
// Use this for initialization
public GameObject test_obj;
void Start () {
OnGUI1();
}
// Update is called once per frame
void Update () {
}
void OnGUI1()
{
//string path_shpere = PathURL + "MySpherePreb.assetbundle";
//StartCoroutine(loadBundleMain(path_shpere));
string path_cube = "D:\\unity\\aaaa2.assetbundle";
StartCoroutine(loadBundleMain(path_cube));
//print(path_cube);
}
private IEnumerator loadBundleMain(string path)
{
WWW bundle = new WWW(path);
// yield return bundle;
Instantiate(bundle.assetBundle.mainAsset);
bundle.assetBundle.Unload(false);
yield return 1;
}
/*
private IEnumerator loadBundleAll(string path)
{
WWW bundle = new WWW(path);
yield return bundle;
//Instantiate(bundle.assetBundle.Load("MyCubePreb"));
//Instantiate(bundle.assetBundle.Load("MySpherePreb"));
yield return 1;
}*/
}
注意点: 有时候不能动态生成。 Object[] os = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
这一步得到的数据为零,从而不能生成动态模型,需要在Resources文件中选择要生成的模型文件(shang.fbx),点击菜单Custom Bundle -> Create Bundel Main。 如下图: