Jump to content

Nested JSON file in Unity

Aspect11

So I am trying to make a script that will write a JSON file like this:

Quote

{

    “gameX” : {

        “username” : “”,

        “timeToComplete” : “”,

        “levelUpgrade” : “”,

        “weaponUpgrade” : “”,

        “armourUpgrade” : “”,

        "totalMoney” : “”,

        “enemiesKilled” : “”,

        “gameCompleted” : “”

    }

}

And this is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.SceneManagement;

public class Statistics : MonoBehaviour {

    public Player player;

    public GameManager manager;

    public EnemyDeathCounter enemyDeaths;

    static float timeCounter;

    static int totalSpent;

    string path = "Assets/Statistics.json";

    void Update() {
        totalTime();
        endGame();
    }

    void totalTime() {
        if(manager.gameInProgressInspector) {
            timeCounter += Time.deltaTime;
        }
    }

    void endGame() {
        if(player.playerDead == true || manager.gameCompleted) {
            // End game
            collectStatistics();
            SceneManager.LoadScene("Leaderboard");
        }
    }

    void collectStatistics() {
        statData statData = new statData();
        string oldDataRaw = File.ReadAllText(path);
        statData oldData = JsonUtility.FromJson<statData>(oldDataRaw);
        //statData.username //DO USERNAME INPUT IN MENU CLASS
        statData.timeToComplete = timeCounter;
        statData.playerLevel = player.playerLevel;
        statData.armourLevel = player.armourLevel;
        statData.weaponLevel = player.weaponLevel;
        statData.totalMoney = player.totalMoneySpent;
        statData.enemiesKilled = enemyDeaths.count;
        statData.gameCompleted = manager.gameCompleted;
        statData.score = completedScore(calculateScore(statData.timeToComplete, statData.playerLevel, statData.armourLevel, statData.weaponLevel, statData.totalMoney, statData.enemiesKilled), statData.gameCompleted);
        string json = JsonUtility.ToJson(statData, true);
        File.WriteAllText(path, json);
    }

    int calculateScore(float timeToComplete, int playerLevel, int armourLevel, int weaponLevel, int totalMoney, int enemiesKilled) {
        if(totalMoney == 0 || enemiesKilled == 0) {
            // TotalMoney and/or enemiesKilled are 0 so need to be excluded
            int score = playerLevel * armourLevel * weaponLevel;
            if(totalMoney == 0 & enemiesKilled == 0) {
                // Both are 0
                score = (score * 100)/Mathf.RoundToInt(timeToComplete);
                return score;
            } else if(totalMoney == 0) {
                // Just totalMoney is 0
                score *= enemiesKilled;
                score = (score * 100)/Mathf.RoundToInt(timeToComplete);
                return score;
            } else if(enemiesKilled == 0) {
                // Just enemiesKilled is 0
                score *= totalMoney;
                score = (score * 100)/Mathf.RoundToInt(timeToComplete);
                return score;
            } else {
                return 0;
            }
        } else {
            // TotalMoney and enemiesKilled are both bigger than 0
            int score = playerLevel * armourLevel * weaponLevel * totalMoney * enemiesKilled;
            score = (score * 100)/Mathf.RoundToInt(timeToComplete);
            return score;
        }
    }

    int completedScore(int score, bool gameCompleted) {
        if(gameCompleted == true) {
            score *= 1;
            return score;
        } else {
            score *= 0;
            return score;
        }
    }

    private class statData {

        public string username;
        public float timeToComplete;
        public int playerLevel;
        public int armourLevel;
        public int weaponLevel;
        public int totalMoney;
        public int enemiesKilled;
        public bool gameCompleted;
        public int score;
    }
}

I have no idea how to make this work. If anyone has any ideas on how I could do this or even if I can do it a better way, they'll be greatly appreciated.

 

Thanks!

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, shadow_ray said:

Could you please apply syntax highlighting to your code :)

 

Unity has a built in json util. https://docs.unity3d.com/Manual/JSONSerialization.html

I know they have a built in json utility library, but it doesn't really help me.

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

17 minutes ago, Aspect11 said:

I know they have a built in json utility library, but it doesn't really help me.

Sorry I didn't read the whole thing

 

Serializable attribute is missing. I think something like this should work.

[Serializable]
public class GameStat{
	public string username;
	//...
}

[Serializable]
public class Game{
	public string gameName;
	public GameStat gameStat;
}

 

You could use lists and structure the data differently.

 

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×