using UnityEngine; using UnityEngine.SceneManagement; using System.Runtime.InteropServices; public class SceneManager : MonoBehaviour, IMethodHandler { // // 声明JavaScript函数用于调试 // [DllImport("__Internal")] // private static extern void DebugToConsole(string message); // WebGL 平台的外部 JavaScript 调用 #if UNITY_WEBGL && !UNITY_EDITOR [DllImport("__Internal")] private static extern void UnityCallback(string callbackName, string tag, string data); #else // 非 WebGL 或编辑器模式下的模拟实现 private static void UnityCallback(string callbackName, string tag, string data) { Debug.Log($"UnityCallback called with: {callbackName} {tag} {data}"); } #endif [System.Serializable] public class SceneLoadData { public string sceneName; public string callbackName; } // 保持单例模式 // public static SceneManager Instance { get; private set; } // private void Awake() // { // if (Instance != null && Instance != this) // { // Destroy(gameObject); // return; // } // Instance = this; // DontDestroyOnLoad(gameObject); // } // 供JavaScript调用的场景加载方法 public void LoadSceneFromJS(string sceneStr) { try { Debug.Log($"Received scene load request: {sceneStr}"); SceneLoadData sceneLoadData = JsonUtility.FromJson(sceneStr); StartCoroutine(LoadSceneAsync(sceneLoadData.sceneName)); UnityCallback(sceneLoadData.callbackName, sceneLoadData.sceneName, ""); Debug.Log($"Scene {sceneLoadData.sceneName} loaded successfully"); } catch (System.Exception e) { #if UNITY_WEBGL && !UNITY_EDITOR // DebugToConsole($"Error loading scene: {e.Message}"); #else Debug.LogError($"Error loading scene: {e.Message}"); #endif } } public void HandleMethod(string methodName, string jsonParameter) { Debug.Log($"Received method call: {methodName} with parameter: {jsonParameter}"); switch (methodName) { case "LoadSceneFromJS": LoadSceneFromJS(jsonParameter); break; default: Debug.LogWarning($"Unknown method: {methodName}"); break; } } private System.Collections.IEnumerator LoadSceneAsync(string sceneName) { // #if UNITY_WEBGL && !UNITY_EDITOR // DebugToConsole($"Starting to load scene: {sceneName}"); // #endif AsyncOperation asyncLoad = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName); while (!asyncLoad.isDone) { float progress = Mathf.Clamp01(asyncLoad.progress / 0.9f); // #if UNITY_WEBGL && !UNITY_EDITOR // DebugToConsole($"Loading progress: {progress * 100}%"); // #endif yield return null; } // #if UNITY_WEBGL && !UNITY_EDITOR // DebugToConsole($"Scene {sceneName} loaded successfully"); // #endif } // 可选:获取当前场景名称的方法 public string GetCurrentSceneName() { return UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; } }