i am trying to add a save system to my android game where the data gets saved in a text file after completing the level the scene
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");
}
}
}
When i tried this in the editor the scenes loaded as usual and the data got saved in the file. I tried changing the write permission to External but it still didn't work. when i built the game as an executable it worked like it should.
Most probably because you get a
DirectoryNotFoundException.works within the Unity Editor since here you have direct access to your file system.
Once you build your application the entire Unity project is compiled and packed according to your target platform and
Assetsfirst of all is not a plain directory anymore and second is read-only.You should rework this and rather write into
Application.persistentDataPathBtw if this is about unlocking levels instead of actually creating a new file for each level I would rather simply store the index of the highest level that is unlocked.