Skip to content

SceneLoader doesnot work in builds #47

@eioe

Description

@eioe

_sceneName is assigend in Editor-Only block.

Fixed script:

using UnityEngine;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Edia {

    [EdiaHeader("EDIA CORE", "Scene Loader", "Loads a additional scene")]
    public class SceneLoader : Singleton<SceneLoader> {
        [Header("Scene Loader")]
#if UNITY_EDITOR
        [SerializeField] private Object sceneAsset;
#endif

        [SerializeField] private string _sceneName;

#if UNITY_EDITOR
        private void OnValidate() {
            // Update the scene name whenever the scene asset changes
            if (sceneAsset != null) {
                string assetPath = AssetDatabase.GetAssetPath(sceneAsset);
                if (!string.IsNullOrEmpty(assetPath))
                    _sceneName = System.IO.Path.GetFileNameWithoutExtension(assetPath);
            }
        }
#endif

        private void Awake() {
            LoadSceneAsync();
        }

        private void LoadSceneAsync() {
            // Load the scene asynchronously
            if (!string.IsNullOrEmpty(_sceneName))
                SceneManager.LoadSceneAsync(_sceneName, LoadSceneMode.Additive);
            else
                Debug.LogError("Scene name is empty, cannot load scene.");
        }

#region Available methods

        /// <summary>
        /// Loads a specified scene asynchronously and additively.
        /// </summary>
        /// <param name="sceneName">The name of the scene to be loaded asynchronously.</param>
        public void LoadScene(string sceneName) {
            _sceneName = sceneName;
            LoadSceneAsync();
        }

        /// <summary>
        /// Unloads a specified scene asynchronously.
        /// </summary>
        /// <param name="sceneName">The name of the scene to be unloaded asynchronously.</param>
        public void UnloadScene(string sceneName) {
            var scene = SceneManager.GetSceneByName(sceneName);
            if (!scene.IsValid()) {
                Debug.LogError($"Scene '{sceneName}' does not exist and cannot be unloaded.");
                return;
            }

            SceneManager.UnloadSceneAsync(sceneName);
        }

#endregion
    }
}

Metadata

Metadata

Assignees

Labels

bugSomething is kaputt!

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions