Skip to content

Instantly share code, notes, and snippets.

@daltonbr
Created September 29, 2020 17:41
Show Gist options
  • Save daltonbr/c2d1aaf73121f58c2a9d46a7b58ed845 to your computer and use it in GitHub Desktop.
Save daltonbr/c2d1aaf73121f58c2a9d46a7b58ed845 to your computer and use it in GitHub Desktop.
Unity Addressables - Spawning an Objects and Loading a scene
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class AssetReferenceUtility : MonoBehaviour
{
public AssetReference objectToLoad;
public AssetReference accessoryObjectToLoad;
private GameObject instantiatedObject;
private GameObject instantiatedAccessoryObject;
private void Start()
{
Addressables.LoadAssetAsync<GameObject>(objectToLoad).Completed += ObjectLoadDone;
}
private void ObjectLoadDone(AsyncOperationHandle<GameObject> obj)
{
if (obj.Status != AsyncOperationStatus.Succeeded) return;
GameObject loadedObject = obj.Result;
Debug.Log("Successfully loaded object.");
instantiatedObject = Instantiate(loadedObject);
Debug.Log("Successfully instantiated object.");
if (accessoryObjectToLoad != null)
{
accessoryObjectToLoad.InstantiateAsync(instantiatedObject.transform).Completed += op =>
{
if (op.Status == AsyncOperationStatus.Succeeded)
{
instantiatedAccessoryObject = op.Result;
Debug.Log("Successfully loaded and instantiated accessory object.");
}
};
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
public class SceneLoader : MonoBehaviour
{
public AssetReference scene;
private AsyncOperationHandle<SceneInstance> handle;
private bool unloaded;
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
// Start is called before the first frame update
void Start()
{
Addressables.LoadSceneAsync(scene,UnityEngine.SceneManagement.LoadSceneMode.Additive).Completed += SceneLoadCompleted;
}
private void SceneLoadCompleted(AsyncOperationHandle<SceneInstance> obj)
{
if (obj.Status == AsyncOperationStatus.Succeeded)
{
Debug.Log("Successfully loaded scene.");
handle = obj;
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.X) && !unloaded)
{
unloaded = true;
UnloadScene();
}
}
void UnloadScene()
{
Addressables.UnloadSceneAsync(handle, true).Completed += op =>
{
if (op.Status == AsyncOperationStatus.Succeeded)
Debug.Log("Successfully unloaded scene.");
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment