Forum rules - please read before posting.

Persist selected inventory item on scene transitions

I was looking for a way to make a selected inventory item persist when the player moves from scene to scene, but I couldn't find a reference in the documentation.

From what I can gather, it looks like the engine manually resets the selected item when the scene initializes (RuntimeInventory -> OnInitialiseScene()), so by the looks of it this functionality is currently unsupported. Is this right or am I missing something?

Comments

  • It's possible with a custom script that relies on hooking into the OnBeforeChangeScene and OnAfterChangeScene custom events - in order to back up the item, and restore it afterwards.

    It's made a little more tricky, however, given that the item is also deselected in Start - but you can use a coroutine to get around this. Something like this ought to do it:

    using UnityEngine;
    using System.Collections;
    using AC;
    
    public class CrossSceneItemSelector : MonoBehaviour
    {
    
        private InvInstance crossSceneInvInstance;
    
        private void OnEnable ()
        {
            EventManager.OnBeforeChangeScene += OnBeforeChangeScene;
            EventManager.OnAfterChangeScene += OnAfterChangeScene;
        }
    
        private void OnDisable ()
        {
            EventManager.OnBeforeChangeScene -= OnBeforeChangeScene;
            EventManager.OnAfterChangeScene -= OnAfterChangeScene;
        }
    
        private void OnBeforeChangeScene (string nextSceneName)
        {
            crossSceneInvInstance = KickStarter.runtimeInventory.SelectedInstance;
        }
    
        private void OnAfterChangeScene (LoadingGame loadingGame)
        {
            if (loadingGame == LoadingGame.No)
            {
                StartCoroutine (ReselectItem ());
            }
        }
    
        private IEnumerator ReselectItem ()
        {
            yield return null;
            KickStarter.runtimeInventory.SelectItem (crossSceneInvInstance);
        }
    
    }
    

    This'll need to be attached to a GameObject that survives scene changes - attaching it to your PersistentEngine prefab will be enough.

  • edited July 2023

    Thanks for the quick response Chris!

    This script seems to be working as intended.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.