動態加載

首先得用ExportResourceBySelection這個類打包預設名字爲:Sphere.unity3d  我的電腦上的保存路徑爲:file:///D:/MyUnity4.6Project/Test/Assets/Resources/prefab/

要選中預設Sphere,右鍵Build AssetBundle From Selection,保存爲:Sphere.unity3d

public class ExportResourceBySelection
{
    [MenuItem("Assets/Build AssetBundle From Selection")]
    static void ExportResource()
    {
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");//打包成.unity3d格式,根據需要你可以是assetbundle格式的,默認名字是:New Resource
        if (path.Length != 0)
        {
            Object[] selections = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            BuildPipeline.BuildAssetBundle(Selection.activeObject, selections, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);
            AssetDatabase.Refresh();
        }
    }
}

如何動態加載prefab實例呢

通過下面這個類:下面採用了兩種方式,一個是Resources.LoadAssetAtPath(),一個是 AssetBundle的 new WWW()

/// <summary>
/// 動態加載Prefab實例
/// </summary>
public class LoadPrefab : MonoBehaviour
{
    /// <summary>
    /// 加載方法枚舉
    /// </summary>
    public enum LoadMethod
    {
        Resources,
        AssetBundle
    }


    /// <summary>
    /// 加載方法
    /// </summary>
    public LoadMethod method;


    // Use this for initialization
    private void Start()
    {
        if (method == LoadMethod.Resources)
            LoadPrefabByResources();
        else
            LoadPrefabByAssetBundle();
    }


    // 通過Resources.LoadAtPath方法動態加載Prefab
    private void LoadPrefabByResources()
    {
        Object prefab = Resources.LoadAssetAtPath("Assets/Prefabs/Cube.prefab", typeof(GameObject));//Resources.LoadAssetAtPath加載unity工程下指定目錄的文件,該

//目錄可以是unity目錄下任意的,而Resources.Load()的侷限性是必須是:Resources路徑下的文件或者子文件

        GameObject cube = (GameObject)Instantiate(prefab);
        cube.transform.parent = transform;
    }


    // 通過AssetBundle方式動態加載Prefab
    private void LoadPrefabByAssetBundle()
    {
        //string path = "http://192.168.12.75/Sphere.unity3d";//加載服務器端的文件
        string path = "file:///D:/MyUnity4.6Project/Test/Assets/Resources/prefab/Sphere.unity3d";//加載本機磁盤路徑的文件
        StartCoroutine(DownLoadPrefab(path));
    }


    // 下載Prefab文件
    private IEnumerator DownLoadPrefab(string path)
    {
        Debug.Log(Application.persistentDataPath);
        WWW www = new WWW(path);
        yield return www;


        if (www.isDone)
        {
            GameObject sphere = (GameObject)Instantiate(www.assetBundle.mainAsset);
            sphere.transform.parent = transform;
            yield return sphere;
            www.assetBundle.Unload(false);
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章