为什么我的Unity场景在写入文件后没有加载



我正在尝试为我的android游戏添加一个保存系统,在完成场景级别后,数据将保存在文本文件中

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;
// Start is called before the first frame update
void Start()
{
Debug.Log("started");
}
// Update is called once per frame
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")
{
SetVar();

SceneManager.LoadScene("Menu");
}
}
public void SetVar()
{
Scene currentScene = SceneManager.GetActiveScene ();
string sceneName = currentScene.name;
if (sceneName == "Level1")
{
File.WriteAllText("Assets/texts/lvl1.txt", "true");
}
else if (sceneName == "Level2")
{
File.WriteAllText("Assets/texts/lvl2.txt", "true");
}
else if (sceneName == "Level3")
{
File.WriteAllText("Assets/texts/lvl3.txt", "true");
}           
else if (sceneName == "Level4")
{
File.WriteAllText("Assets/texts/lvl4.txt", "true");
}
else if (sceneName == "Level5")
{
File.WriteAllText("Assets/texts/lvl5.txt", "true");   
}
else if (sceneName == "Level6")
{
File.WriteAllText("Assets/texts/lvl6.txt", "true");
}
}
}

当我在编辑器中尝试时,场景像往常一样加载,数据被保存在文件中。我尝试将写入权限更改为"外部",但仍然无效。当我将游戏构建为可执行程序时,它的工作原理是应该的。

很可能是因为您得到了DirectoryNotFoundException

File.WriteAllText("Assets/texts/lvl1.txt", "true");

在Unity编辑器中工作,因为在这里您可以直接访问您的文件系统。

一旦你构建了你的应用程序,整个Unity项目就会根据你的目标平台进行编译和打包,Assets首先不再是一个普通的目录,其次是只读的。

您应该对此进行返工,并将其写入Application.persistentDataPath


Btw如果这是关于解锁级别,而不是为每个级别创建一个新文件,我宁愿简单地存储解锁的最高级别的索引。

public void SetVar()
{
var currentScene = SceneManager.GetActiveScene();
// e.g. "Level5"
var currentSceneName = currentScene.name;
// cut away the "Level" part of the name -> only keep index
// e.g. "5"
currentSceneName.Replace("Level", "", StringComparison.InvariantCultureIgnoreCase);
// if can not be parsed to an index -> ignore
if (!int.TryParse(currentSceneName, out var currentIndex))
{
return;
}
// get the levels folder and file path
var levelsFolder = Path.Combine(Application.persistentDataPath, "levels");
var levelsFile = Path.Combine(levelsFolder, "passed.txt");
// default index if no save file exists so far
var lastPassedIndex = -1;     
if (File.Exists(levelsFile))
{
// otherwise read the file and overwrite "lastPassedIndex"
var lastPassedText = File.ReadAllText(levelsFile);
int.TryParse(lastPassedText, out lastPassedIndex);
}
// is this level actually higher than the currently highest?
if (currentIndex > lastPassedIndex)
{
// if folder doesn't exist 
if (!Directory.Exists(levelsFolder))
{
// create it
Directory.CreateDirectory(levelsFolder);
}
// store the current index
File.WriteAllText(levelsFile, currentIndex.ToString());
}
}

最新更新