How to log player's playing time and walking distance in one scene?

Hi Unity Professions,

I am developing a local game that I have to log each player’s playing time and total walking distance in one scene.
Players do not need to see their time and distance in game-play.
I just have to achieve the data after the game-play.
Is there a method that the data is generated to a local file once the game is terminated?

Thank you community!

Hi!
There is no one method that does exactly this, but you can start a timer at the beginning of the game to measure play time and use that time to help calculate the distance.

Here is a forum post about a similar question:
https://forum.unity.com/threads/how-to-get-game-played-time.1236208

I might have gone a little overboard with this example, but creating it was fun.

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

[Serializable]
public class GameLogData
{
    public float totalDistance;
    public float totalTimeSpentPlaying;
    public string timestamp;
}

[Serializable]
public class GameLogDataList
{
    public List<GameLogData> gameLogs = new List<GameLogData>();
}

public class Logger : MonoBehaviour
{
    [SerializeField]
    private float totalDistance = 0f;
    [SerializeField]
    private float totalTimeSpentPlaying = 0f;
    private Vector3 previousPosition;

    void Update()
    {
        // Calculate the distance traveled since the last frame
        float distanceTraveled = Vector3.Distance(transform.position, previousPosition);

        // Update the total distance
        totalDistance += distanceTraveled;

        // Update the previous position for the next frame
        previousPosition = transform.position;

        // Increment total time spent playing
        totalTimeSpentPlaying += Time.deltaTime;
    }

    void OnDisable()
    {
        string directoryPath = Path.Combine(Application.dataPath, "Logs");
        string filePath = Path.Combine(directoryPath, "GameLog.json");
        Debug.Log($"Saving to: {filePath}");

        // Ensure the directory exists
        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
        }

        // Read existing JSON file
        GameLogDataList gameLogDataList;
        try
        {
            string jsonFile = File.ReadAllText(filePath);
            gameLogDataList = JsonUtility.FromJson<GameLogDataList>(jsonFile);
        }
        catch (FileNotFoundException)
        {
            // If the file does not exist, create a new list
            Debug.LogWarning("File not found, creating new list");
            gameLogDataList = new GameLogDataList();
        }

        // Add new data to the list
        GameLogData gameLogData = new GameLogData
        {
            totalDistance = totalDistance,
            totalTimeSpentPlaying = totalTimeSpentPlaying,
            timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        };

        gameLogDataList.gameLogs.Add(gameLogData);

        try
        {
            // Write the updated list back to the JSON file
            string json = JsonUtility.ToJson(gameLogDataList);
            File.WriteAllText(filePath, json);
        }
        catch (Exception e)
        {
            Debug.LogError($"Error writing to file: {e.Message}");
        }
    }
}