1、打包
打图集
打预制体
打图片
打AB包
所有打出来的包都存到 Assets/StreamingAssets 目录下
using UnityEditor;
public class CreateAssetBundles
{
[MenuItem("Assets/Build AssetBundles")]
static void BuildAllAssetBundles()
{
BuildPipeline.BuildAssetBundles("Assets/StreamingAssets", BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.Android);
}
}
2、加载和读取
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.U2D;
using UnityEngine.UI;
public class test1 : MonoBehaviour
{
public Image pic;
void Start()
{
//加载预制
var myLoadedAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "texture"));
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
return;
}
var prefab = myLoadedAssetBundle.LoadAsset<GameObject>("Texture");
Instantiate(prefab);
//加载图片
myLoadedAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "img"));
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
return;
}
var sprite = myLoadedAssetBundle.LoadAsset<Sprite>("1");
pic.sprite = sprite;
//加载图集
myLoadedAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "imgs"));
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
return;
}
var spriteAtlas = myLoadedAssetBundle.LoadAsset<SpriteAtlas>("11");
sprite = spriteAtlas.GetSprite("2");
pic.sprite = sprite;
}
void Update()
{
}
}
预制体打包时图集里资源会不显示,需要创建一个常驻的监听类
Const.Bundle_SpriteAtlas 是图集打包的名字,预制体里的图集必须打包。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.IO;
using UnityEngine.U2D;
public class SpriteAtlasLoader : MonoSingleton<SpriteAtlasLoader>
{
protected override void Awake()
{
base.Awake();
SpriteAtlasManager.atlasRegistered += AtlasRegistered;
SpriteAtlasManager.atlasRequested += AtlasRequested;
}
void AtlasRegistered(SpriteAtlas spriteAtlas)
{
//Debug.LogFormat("AtlasRegistered tag={0}.", spriteAtlas.tag);
}
void AtlasRequested(string tag, System.Action<SpriteAtlas> callback)
{
float startTime = Time.realtimeSinceStartup;
var assetName = string.Format("{0}.spriteatlas", tag);
var bundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, Const.Bundle_SpriteAtlas));
var spriteAtlas = bundle.LoadAsset<SpriteAtlas>(assetName);
//var spriteAtlas = (SpriteAtlas)BundleManager.Instance.LoadBundle(Const.SPRITE_ATLAS_BASE_PATH, assetName);
//Debug.LogFormat("//AtlasRequested tag={0}, loading time={1:N8}", tag, (Time.realtimeSinceStartup - startTime));
callback(spriteAtlas);
}
}