在Unity中創建游戲對象的方法有 3 種:
- 第一種是將物體模型資源由 Project 視圖直接拖曳到 Hierarchy 面板中;
- 第二種是在 Unity 3D 菜單 GameObject 中創建 Unity 3D 自帶的游戲對象,如 Cube、Camera、Light 等;
- 第三種是利用腳本編程,動態創建或刪除游戲對象。
本文嘗試采用第三種方法,即利用腳本動態加載3D模型文件,從而創建游戲對象。
網上搜索“Unity3d 動態加載fbx模型文件”,大部分都是對文章https://blog.csdn.net/ldkcumt/article/details/51098206的轉載,先親身做一下實踐。
Unity版本:Unity 2018.3.7f1 (64-bit) 隨VS2017一起安裝。
方法一:
1 將模型拖動到場景中 ,調整好位置。(制作prefab預制體需要)
2 新建Resources(如果工程中有的話 就不用新建了,Resources.Load調用的就是該文件夾下的資源),在該文件夾下建一個prefab,將上面的模型拖動到這個prefab上
3 刪除場景中的該物體模型
4 編寫腳本,把它隨便扔給一個GameObject
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class LoadFBX : MonoBehaviour 6 { 7 public string url; 8 // Start is called before the first frame update 9 void Start() 10 { 11 GameObject gFbx = (GameObject)Instantiate(Resources.Load("che")); 12 } 13 14 // Update is called once per frame 15 void Update() 16 { 17 18 } 20 }
方法二:
1 按方法1 制作prefab (注意調整好位置)
2 然后使用AssetBundle導出包
3 這時可以看到導出的.AssetBundle文件了
4 編寫代碼
第2步詳解:參考https://www.jianshu.com/p/f4c685cf487a
1 using UnityEngine; 2 using System.Collections; 3 using UnityEditor; 4 using System.IO; 5 public class AssetBundleBuilder 6 { 7 [MenuItem("Assets/Build AssetBundle")] 8 static public void BuildAssetBundle() 9 { 10 Caching.ClearCache(); 11 string path = Application.streamingAssetsPath + "/" + "AssetBundles" + "/" + "Windows"; 12 if (!Directory.Exists(path)) 13 { 14 Directory.CreateDirectory(path); 15 } 16 BuildPipeline.BuildAssetBundles(path, 0, EditorUserBuildSettings.activeBuildTarget); 17 AssetDatabase.Refresh(); 18 } 19 }
加載代碼修改:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class LoadFBX : MonoBehaviour 6 { 7 public string url; 8 // Start is called before the first frame update 9 void Start() 10 { 11 //GameObject gFbx = (GameObject)Instantiate(Resources.Load("che")); 12 string name = "che.first"; 13 url = "file://C:/Users/yakong/Documents/FirstUnity3d/Assets/StreamingAssets/AssetBundles/Windows/"; 14 StartCoroutine(LoadAsset(url, name)); 15 } 16 17 // Update is called once per frame 18 void Update() 19 { 20 21 } 22 23 // LoadAssert 24 public IEnumerator LoadAsset(string url, string Scname) 25 { 26 WWW www = new WWW(url + Scname); 27 yield return www; 28 AssetBundle bundle = www.assetBundle; 29 foreach (var name in bundle.GetAllAssetNames()) 30 { 31 Debug.Log(name); 32 if (name != "") 33 { 34 GameObject go = (GameObject)Instantiate(bundle.LoadAsset(name)); 35 } 36 } 37 } 38 }
PS:直接使用www.assetBundle.mainAsset時運行為null,參考https://stackoverflow.com/questions/42775797/cannot-load-an-asset-bundle解決!
最終的啟動運行加載效果: