去年某項(xiàng)目需要從后端服務(wù)器上加載FBX模型,但是整個項(xiàng)目中只有很少的地方需要用到動態(tài)模型替換,并且項(xiàng)目交付后需要外行人員也能輕松上手更換需要動態(tài)加載的模型,所以需要實(shí)現(xiàn)一個簡單的模型打包和動態(tài)模型加載功能。
FBX模型打包為.assetbundle文件
1.創(chuàng)建一個新的腳本,編寫如下代碼
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class ExportAssetBundles : MonoBehaviour
{
//在Unity編輯器中添加菜單
[MenuItem("AssetBundle / 打包選中的文件")]
static void Export()
{
// 打開保存面板,獲得用戶選擇的路徑
string path = EditorUtility.SaveFilePanel("保存文件", "", "模型", "assetbundle");
if (path.Length != 0)
{
// 選擇的要保存的對象
Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
//打包 成AssetBundle
BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);
}
}
}
2.回到unity中,左上角工具欄出現(xiàn)AssetBundle,點(diǎn)擊AssetBundle,然后選中你需要打包的FBX模型文件,點(diǎn)擊“打包選中文件”,選擇保存路徑即可。(需要注意的是,模型文件的名稱應(yīng)與上圖代碼中13行的第三個參數(shù)相同)

3.打包FBX模型之后將其放入能夠訪問并下載的服務(wù)器
FBX模型在線替換的具體實(shí)現(xiàn)
1.在需要加載模型的地方編寫如下代碼(代碼中第13行為服務(wù)器上準(zhǔn)備好的.assetbundle文件)文章來源:http://www.zghlxwxcb.cn/news/detail-509768.html
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class GameManager : MonoBehaviour
{
private void Start()
{
Screen.SetResolution(3840, 2160, false);
StartCoroutine(LoadModel2("http://localhost//模型.assetbundle"));
}
IEnumerator LoadModel2(string url)
{
var uwr = UnityWebRequestAssetBundle.GetAssetBundle(url);
yield return uwr.SendWebRequest();
// Get an asset from the bundle and instantiate it.
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr);
var loadAsset = bundle.LoadAssetAsync<GameObject>("Assets/Art/Model/模型.FBX");
yield return loadAsset;
Instantiate(loadAsset.asset,transform);
var mx = transform.Find("模型(Clone)");
mx.transform.localPosition = new Vector3(0,0,0);
mx.transform.localEulerAngles = Vector3.zero;
}
}
2.運(yùn)行上面代碼即可實(shí)現(xiàn)動態(tài)加載FBX模型(請注意在打包項(xiàng)目之前應(yīng)先將第一步的代碼注釋,否則將打包失敗)文章來源地址http://www.zghlxwxcb.cn/news/detail-509768.html
到了這里,關(guān)于Unity動態(tài)加載外部服務(wù)器上的FBX模型的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!