Unity 動態載入Prefab

2021-09-22 08:02:53 字數 1279 閱讀 6245

第一種方法,從resources資料夾讀取prefab

assets/resources是unity中的乙個特殊資料夾,放在這個資料夾裡的資源包括prefab可以被**動態載入。

gameobject prefab = (gameobject)resources.load("prefabs/character");

instantiate(prefab);

第二種方法,絕對路徑讀取prefab

這種方法僅限editor模式使用,在製作外掛程式的時候會經常使用的方法。

gameobject gb = assetdatabase.loadassetatpath("assets/prefabs/character.prefab", typeof(gameobject)) as gameobject; //該函式返回乙個object,需要強轉為gameobject,第乙個引數為完整絕對路徑,第二個引數為prefab名  

instantiate(gb);

第三種方法,把prefab打包成assetbundle並且使用assetbundle相關api動態載入

1)在inspector面板中把prefab資源打包。

2)編寫assetbundle生成工具

plugins/editor也是unity中的乙個特殊資料夾,在plugins下的指令碼的編譯優先順序高於普通指令碼。

在asset下建立資料夾plugins,再在plugins下建立資料夾editor,在plugins/editor下建立指令碼createassetbundles.cs。

using unityeditor;

using system.io;

public class createassetbundles

//使用lzma演算法打包

buildpipeline.buildassetbundles(assetbundlepath, buildassetbundleoptions.none, buildtarget.standalonewindows64);

}}

3)建立指令碼載入prefab

建立載入指令碼assetbundleloader.cs。

using system.collections;

using system.collections.generic;

using unityengine;

public class assetbundleloader

}

原文:

Unity設定Prefab中children的變數

已有結構 prefab p gameobject a script aaa id title.gameobbject b 目的 建立乙個prefab的clone並設定aaa的屬性id 實現 gameobject tmp gameobject gameobject.instantiate p,some...

unity的prefab(預設)例子

prefab用於預先設定一些控制項,在需要的時候直接引用,簡化開發,當然,你完全可以用寫 解決 在場景內新建乙個空物體,繫結乙個指令碼 void start 拖到project標籤欄裡面,儲存為prefab,場景內建立的空物體可以刪除了 重新在場景內建立乙個物體,繫結新建的指令碼 public tr...

Unity 動態載入與記憶體(二)

unity幾種動態載入prefab方式的差異 其實存在3種載入prefab的方式 一是靜態引用,建乙個public的變數,在inspector裡把prefab拉上去,用的時候instantiate 二是resource.load,load以後instantiate 三是assetbundle.loa...