前言
Unity Addressables学习笔记—汇总
正文
1.创建一个新场景
我是创建在Resources/Scenes目录下,如图:
2.为场景创建一个Addressables的Group
Game1Group就是我新创建的一个Group用来存放场景1的所有资源,分组的配置跟Remote一样,都是远程的,加载地址是我本地启动的web服务器地址,URL里WebGL那个目录也不是必须的,根据自己实际的来。
3.把新场景和场景里用到的资源全部拖入到Game1Group里
上边的图就是拖完的状态。
4.在初始化的场景里添加代码,用Addressables的方式加载新的场景Game1.
我是在最开始的场景里图片1那个开始按钮上加了个点击事件去触发加载Game1这个场景的
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
private Sprite sprite;
public Button btn;
public List<string> list;
void Start()
{
//Addressables.Instantiate("Play Button").Result.transform.position = new Vector3(2f, 2f);
foreach (string name in list)
{
Addressables.LoadAssetAsync<GameObject>(name).Completed += SpriteLoadedObj;
}
//PlayerPrefs.DeleteKey(Addressables.kAddressablesRuntimeDataPath);
Addressables.LoadAssetAsync<Sprite>("Play Button Img").Completed += SpriteLoaded;
}
private void SpriteLoaded(AsyncOperationHandle<Sprite> obj)
{
switch (obj.Status)
{
case AsyncOperationStatus.Succeeded:
sprite = obj.Result;
Debug.Log(sprite);
btn.image.sprite = sprite;
break;
case AsyncOperationStatus.Failed:
Debug.LogError("Sprite load failed.");
break;
default:
//case AsyncOperationStatus.None:
break;
}
}
private void SpriteLoadedObj(AsyncOperationHandle<GameObject> obj)
{
switch (obj.Status)
{
case AsyncOperationStatus.Succeeded:
GameObject a = Instantiate(obj.Result);
a.transform.position = new Vector2(2f, 2f);
break;
case AsyncOperationStatus.Failed:
Debug.LogError("Sprite load failed.");
break;
default:
//case AsyncOperationStatus.None:
break;
}
}
// Update is called once per frame
void Update()
{
}
public void onClick()
{
Addressables.LoadSceneAsync("Game1");
}
}
5.场景1:用Addressables创建一个对象,在Hierarchy里拖进去一个对象,一共2个对象
下边是场景1拖进去的一个对象
下边是GameObject上随便绑定一个C#脚本再去创建一个对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class Game1Controller : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Addressables.LoadAssetAsync<GameObject>("Layer 10").Completed += SpriteLoadedObj;
}
// Update is called once per frame
private void SpriteLoadedObj(AsyncOperationHandle<GameObject> obj)
{
switch (obj.Status)
{
case AsyncOperationStatus.Succeeded:
GameObject a = Instantiate(obj.Result);
a.transform.position = new Vector2(2f, 2f);
break;
case AsyncOperationStatus.Failed:
Debug.LogError("Sprite load failed.");
break;
default:
//case AsyncOperationStatus.None:
break;
}
}
}