Unity2017 Assetbundle 打包、加载

打包(脚本放到Editor文件夹下):

    [MenuItem("Framework/Build iPhone Resource", false, 100)]
    public static void BuildiPhoneResource()
    {
        BuildTarget target;
        target = BuildTarget.iOS;
        BuildAssetResource(target);
    }

    [MenuItem("Framework/Build Android Resource", false, 101)]
    public static void BuildAndroidResource()
    {
        BuildAssetResource(BuildTarget.Android);
    }

    [MenuItem("Framework/Build WebGL Resource", false, 101)]
    public static void BuildWebGLResource()
    {
        BuildAssetResource(BuildTarget.WebGL);
    }

    [MenuItem("Framework/Build Windows Resource", false, 102)]
    public static void BuildWindowsResource()
    {
        BuildAssetResource(BuildTarget.StandaloneWindows);
    }

    /// 
    /// 生成绑定素材
    /// 
    private static void BuildAssetResource(BuildTarget _target)
    {
        string streamPath = Application.streamingAssetsPath;
        BuildPipeline.BuildAssetBundles(streamPath, BuildAssetBundleOptions.None, _target);
        AssetDatabase.Refresh();
    }

将需要打包的素材(最好是做成预设)在AssetLabels面板设置好AssetBundle名称和后缀名之后就可以在菜单栏的Framework菜单下进行打包了,需要注意选则要发布的平台。如果设置的AssetBundle名称及后缀相同,则会打到一个AssetBundle包中。

加载:

 string _path = string.Format("{0}/{1}.asset", Application.streamingAssetsPath, _name);
#if !UNITY_WEBGL||UNITY_EDITOR
                AssetBundle _ab = AssetBundle.LoadFromFile(_path);                
                Transform newTarget = Instantiate(_ab.LoadAsset(_name) as GameObject, target).transform;
                newTarget.DOScale(new Vector3(0, 0, 0), 0.2f).From();
                _ab.Unload(false);
#else
                StartCoroutine(GetAsset(_path,_name));
#endif
 private IEnumerator GetAsset(string _path,string _name)
    {
        WWW _www = new WWW(_path);
        yield return _www;
        if (null == _www.error)
        {
            AssetBundle _ab = _www.assetBundle;
            Transform newTarget = Instantiate(_ab.LoadAsset(_name) as GameObject, target).transform;
            newTarget.DOScale(new Vector3(0, 0, 0), 0.2f).From();
            _ab.Unload(false);
        }
        else
        {
            print(_www.error);
        }
    }
至此看起来和之前都没有啥不同,但是!!5.0之前的Unity打包的时候会在包里指定mainAsset,现在去获取的话只能得到null (/ □ \),所以加载的时候一定要注意,使用LoadAssett(Name)的方式进行加载。

你可能感兴趣的:(Unity)