unity-game-engine

How to retrieve AssetReference from Scene?


I have a Scene marked as Addressable. Given the Scene itself, is it possible to get the AssetReference for that scene?

For example, in the following code snippet, what would ?? need to be?

Scene activeScene = SceneManager.GetActiveScene();

// What can I call here to get the AssetReference?
AssetReference activeSceneReference = ??;

Solution

  • If this is possible at all I honetsly can't tell since I never worked with Addressables so far.

    However, following the APIs this might be possible but requires multiple steps:

    Since the activeScene is a loaded scene and the same scene can be loaded multiple times via additive loading it is not actually an asset anymore and therefore doesn't have an asset reference at all.


    So the first step is actually

    Get the asset for a loaded scene

    Having your loaded scene you can still get its original asset path via Scene.path.

    var activeScene = SceneManager.GetActiveScene();
    var activeScenePath = activeScene.path;
    

    And then use AssetDatabase.LoadAssetAtPath to load the original asset

    var activeSceneAsset = AssetDataBase.LoadAssetAtPath<Scene>(activeScenePath);
    

    Now that we have the actual asset of the loaded scene we can

    Get the GUID of an Asset

    Having already the asset activeSceneAsset you can use AssetDatabase.TryGetGUIDAndLocalFileIdentifier in order to optain the GUID we need in the last step:

    if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(activeSceneAsset, out var guid, out var file))
    {
        // TODO see below
    }
    

    and now having that guid we can use it in order to

    Get the AssetReference via the GUID

    The reason why we wanted to get the GUID is because we can now use it for the AssetReference constructor taking the GUID as parameter:

    var activeSceneReference = new AssetReference(guid);
    

    NOTE: All this is ofcourse only possible in the Unity Editor itself since AssetDataBase does not exist outside of it.