Unity安卓游戏写入文件后场景无法加载问题求助
问题诊断与解决方案
核心问题是安卓平台下Assets/texts/属于只读目录,直接调用File.WriteAllText会抛出IO异常,导致后续的SceneManager.LoadScene("Menu")代码被中断执行。Unity编辑器和PC端的Assets目录是可写的,但安卓打包后Assets会被打包进APK,完全只读。
具体修复步骤:
- 改用Unity提供的可读写持久化路径:
Application.persistentDataPath,这个路径在安卓系统中对应/Android/data/[你的包名]/files/,无需额外权限即可读写。 - 简化重复的判断逻辑,通过场景名直接拼接存档文件名,避免冗余代码。
- 添加异常捕获,方便排查安卓端的隐藏错误(安卓默认看不到控制台日志)。
修改后的完整代码:
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using System.IO; public class CollisionHandler : MonoBehaviour { Rigidbody2D playerRb; public GameObject targ; void Start() { Debug.Log("started"); } void Update() { } void OnCollisionEnter2D(Collision2D coll) { Debug.Log("collided"); if (coll.gameObject.tag == "DANGER") { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } else if (coll.gameObject.tag == "Finish") { try { SetVar(); SceneManager.LoadScene("Menu"); } catch (Exception e) { // 捕获异常并打印,安卓端可以通过LogCat查看 Debug.LogError($"存档失败:{e.Message}"); // 可选:把异常信息写入持久化路径的日志文件 File.WriteAllText(Path.Combine(Application.persistentDataPath, "error.log"), e.ToString()); } } } public void SetVar() { Scene currentScene = SceneManager.GetActiveScene(); string sceneName = currentScene.name; // 拼接持久化路径和存档文件名 string savePath = Path.Combine(Application.persistentDataPath, $"{sceneName}.txt"); File.WriteAllText(savePath, "true"); Debug.Log($"存档已写入:{savePath}"); } }
额外注意事项:
- 确保
Menu场景已经添加到Build Settings的场景列表中,否则SceneManager.LoadScene会失败。 - 如果需要读取存档,同样要使用
Application.persistentDataPath路径,不能再读Assets下的文件。 - 安卓端调试时,可以通过Android Studio的LogCat查看
Debug.Log和Debug.LogError的输出,确认存档路径和错误信息。
内容的提问来源于stack exchange,提问作者Belbel 334
相关产品推荐
相关产品推荐

