You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity双场景切换问题:返回丢失修改与Additive模式无法切场景

Unity双场景切换问题解决方案

问题原因分析

  • 使用SceneManager.LoadScene("Scene1"):默认采用LoadSceneMode.Single模式,会卸载当前所有场景并重新加载目标场景,因此之前对场景的修改会随场景重新加载而丢失。
  • 使用SceneManager.LoadScene("Scene1", LoadSceneMode.Additive):采用叠加加载模式,会保留当前场景并加载目标场景,但Unity不会自动将新场景设为活动场景,因此视觉上不会切换到新场景。

解决方案一:保留场景修改+切换到新场景

适合需要保留原场景全局对象(如游戏管理器、音效控制器),同时切换到新场景的场景。核心步骤是叠加加载后设置活动场景,可选卸载旧场景。

代码示例

using UnityEngine.SceneManagement;
using UnityEngine;
using System.Collections;

public class SceneSwitcher : MonoBehaviour
{
    // 调用此方法切换场景并保留修改
    public void SwitchSceneWithRetain(string targetSceneName)
    {
        StartCoroutine(SwitchSceneCoroutine(targetSceneName));
    }

    private IEnumerator SwitchSceneCoroutine(string targetSceneName)
    {
        // 记录当前活动场景(后续可选择卸载)
        Scene currentActiveScene = SceneManager.GetActiveScene();

        // 异步叠加加载目标场景
        AsyncOperation loadOp = SceneManager.LoadSceneAsync(targetSceneName, LoadSceneMode.Additive);
        
        // 等待加载完成
        while (!loadOp.isDone)
        {
            yield return null;
        }

        // 获取加载完成的场景并设置为活动场景
        Scene targetScene = SceneManager.GetSceneByName(targetSceneName);
        if (targetScene.isLoaded)
        {
            SceneManager.SetActiveScene(targetScene);
            
            // 可选:卸载原场景(如果不需要保留)
            SceneManager.UnloadSceneAsync(currentActiveScene);
        }
    }
}

解决方案二:保存对象状态+普通场景加载

适合不需要保留原场景对象,仅需保存场景内特定对象状态的场景。通过手动序列化对象状态,在场景加载时恢复。

代码示例(以开关对象为例)

using UnityEngine;

public class PersistentSwitch : MonoBehaviour
{
    [SerializeField] private bool isSwitchActivated;

    private void Awake()
    {
        // 加载场景时恢复状态
        if (PlayerPrefs.HasKey(GetStateKey()))
        {
            isSwitchActivated = PlayerPrefs.GetInt(GetStateKey()) == 1;
            UpdateSwitchVisual();
        }
    }

    private void OnDestroy()
    {
        // 场景卸载前保存状态
        PlayerPrefs.SetInt(GetStateKey(), isSwitchActivated ? 1 : 0);
        PlayerPrefs.Save();
    }

    // 切换开关状态的方法
    public void ToggleSwitch()
    {
        isSwitchActivated = !isSwitchActivated;
        UpdateSwitchVisual();
    }

    // 更新开关视觉表现
    private void UpdateSwitchVisual()
    {
        GetComponent<SpriteRenderer>().color = isSwitchActivated ? Color.green : Color.gray;
    }

    // 生成唯一的状态存储键
    private string GetStateKey()
    {
        return $"{gameObject.scene.name}_{gameObject.name}_SwitchState";
    }
}

选择建议

  • 若需保留全局场景对象(如跨场景的系统管理器),优先选解决方案一
  • 若仅需保存场景内特定对象的状态,优先选解决方案二

内容的提问来源于stack exchange,提问作者Jiminion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 22:12:45