Error unloading scenes inside package

Hey guys!

I’m getting a really weird error when unloading scenes and I don’t know if I’m doing anything wrong. I’m creating a package in Unity and I have some scenes inside this package. When I try to load these scenes, everything works fine, but when I try to unload them, I get an error that says:

ArgumentException: Scene to unload is invalid

My code looks like this:

        public virtual async Task UnloadLocalScene(string scene)
        {
            if (!IsSceneLoaded(scene))
                return;

            AsyncOperation operation = UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync(scene);
            while (!operation.isDone) await Task.Yield();

            Debug.Console.Log($"[SceneManager] Scene {scene} unloaded");
        }

        protected virtual bool IsSceneLoaded(string scenePath)
        {
            string sceneName = Path.GetFileNameWithoutExtension(scenePath);
            Scene scene = UnityEngine.SceneManagement.SceneManager.GetSceneByName(sceneName);
            return scene.IsValid() && scene.isLoaded;
        }

It is important to notice the code always works with scenes outside packages (in Assets). I understand that this may be something you are not intended to do since packages have Samples, but I’m curious about why this may be happening.

Thank you!

PD: This error is happening to me in unity2022 and unity 6

I haven’t played much with scenes contained in Packages.

The two main reasons I’ve seen errors unloading scenes are:

  • the scene isn’t presently loaded (this includes scenes you JUST asked to load, since scenes do not load until end of frame)
  • there are no other scenes loaded (there must always be a scene loaded)

Did you log the scene path?
Packages have different paths than usual, and depending on how the package is installed the path may even be different between an embedded package (located under Packages) and a package installed “from disk”.

Not sure but if you use the scene name I believe the scene needs to be in the scene list for builds.
You also run the risk of getting a scene by name which may not be unique in the project, ie there may be more than one scene named “Samples” hence why I would always refrain from using “scene name” based methods.

If need be, I’d have a ScriptableObject that stores the scene reference, their paths and names so that these are available at runtime. I use a SceneReference class that neatly separates the editor-only info and keeps it up to date for runtime. It also allows referencing scenes in the Inspector to avoid any sort of “by name” or “by index” code which are both brittle since both name and index can change for a plethora of reasons.