Home > database >  Unity saving the player's username and score to a text file
Unity saving the player's username and score to a text file

Time:04-25

I made an input field in which the user types their username and a "Send data" button that sends the username and the score to a text file, However, the score isn't saving for some reason. The output says 0 but the score is increasing in-game. I can't seem to figure out what is causing this.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using UnityEngine.Networking;

public class ScoreScript : MonoBehaviour
{
    public Text MyscoreText, userTxt;
    private int ScoreNum;

    // Start is called before the first frame update
    void Start()
    {
        ScoreNum = 0;
    }

    private void OnTriggerEnter2D(Collider2D Diamond)
    {
        if (Diamond.tag == "Diamond")
        {
            // Player's score increases when they collide with a diamond
            ScoreNum  ;
            Destroy(Diamond.gameObject);
            MyscoreText.text = "Score: "   ScoreNum;
        }
    }

    public void SaveScore()
    {
        // Saves the username and score to a text file
        string tmp = userTxt.text   ","   ScoreNum.ToString();
        System.Text.UnicodeEncoding encode = new System.Text.UnicodeEncoding();
        byte[] byteData = encode.GetBytes(tmp);
        Debug.Log(tmp);
        if (!File.Exists(Application.absoluteURL   @"\hiscore.txt"))
        {
            FileStream oFileStream = null; 
            oFileStream = new FileStream(Application.dataPath   @"\hiscore.txt", FileMode.Create);
            oFileStream.Write(byteData, 0, byteData.Length);
            oFileStream.Close();
        }
        else
        {
            using (StreamWriter stream = File.AppendText(Application.dataPath   @"\hiscore.txt"))
            {
                stream.WriteLine(tmp);
            }
        }
    }
}

CodePudding user response:

I tested your code and every time I call the method SaveScore() the program creates a new hiscore.txt file as if one wasn't created before. I replaced the "Aplication.absoluteURL" with "Application.dataPath" and the program functioned as intended, so now the method SaveScore() looks like this:

public void SaveScore()
{
    string tmp = userTxt.text   ","   ScoreNum.ToString();
    System.Text.UnicodeEncoding encode = new System.Text.UnicodeEncoding();
    byte[] byteData = encode.GetBytes(tmp);
    Debug.Log(tmp);
    if (!File.Exists(Application.dataPath   @"\hiscore.txt"))
    {
        FileStream oFileStream = null; 
        oFileStream = new FileStream(Application.dataPath   @"\hiscore.txt", FileMode.Create);
        oFileStream.Write(byteData, 0, byteData.Length);
        oFileStream.Close();
    }
    else
    {
        using (StreamWriter stream = File.AppendText(Application.dataPath   @"\hiscore.txt"))
        {
            stream.WriteLine(tmp);
        }
    }
}

CodePudding user response:

Two issues here, I think. The first seems like it could be because you're using File.AppendText in the else section of your code, which should be UTF-8 encoded text, per the documentation:

Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.

But you're not encoding the text there like you are for the section above. What I would suggest instead is to just use File.AppendAllText, which has the following benefits:

  1. Creates the file if it doesn't exist, otherwise appends to the file. This means that you don't need to check if the file exists and write it one way, else write it another, you can just call the one command and it creates-or-appends.
  2. Lets you pass strings instead of byte arrays, so you can just write your strings without needing to bother with encoding.

Second big issue I think is when you check if the file exists, you're checking a URL and not a path:

if (!File.Exists(Application.absoluteURL   @"\hiscore.txt"))

But then you're writing/appending to a file at a path:

oFileStream = new FileStream(Application.dataPath   @"\hiscore.txt", FileMode.Create);
[...]
using (StreamWriter stream = File.AppendText(Application.dataPath   @"\hiscore.txt"))

The if statement is checking Application.absoluteURL and the if/else is using Application.dataPath.

Another issue you might be having is if you're having permissions troubles and you're not able to get write access to the file, like if you had created it when you had sudo privileges but now you don't (sudo expires! did you try restarting?) or if your application is in a protected Windows directory or something.

Are you sure you haven't disabled errors in the Unity Console? I would also try deleting the hiscore.txt file (spelling here? Are you checking hiscore or highscore?) and see if you get updates.

Finally also, and deleting the file might make this clear, it's not obvious here how the save function is getting called, so it's also very possible you've inadvertently broken that callback somehow, like changing the name or something.

  • Related