Unity动态加载外部服务器上的FBX模型

去年某项目需要从后端服务器上加载FBX模型,但是整个项目中只有很少的地方需要用到动态模型替换,并且项目交付后需要外行人员也能轻松上手更换需要动态加载的模型,所以需要实现一个简单的模型打包和动态模型加载功能。

FBX模型打包为.assetbundle文件

1.创建一个新的脚本,编写如下代码

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中,左上角工具栏出现AssetBundle,点击AssetBundle,然后选中你需要打包的FBX模型文件,点击“打包选中文件”,选择保存路径即可。(需要注意的是,模型文件的名称应与上图代码中13行的第三个参数相同)

3.打包FBX模型之后将其放入能够访问并下载的服务器

FBX模型在线替换的具体实现

1.在需要加载模型的地方编写如下代码(代码中第13行为服务器上准备好的.assetbundle文件)

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.运行上面代码即可实现动态加载FBX模型(请注意在打包项目之前应先将第一步的代码注释,否则将打包失败)

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值