Files
Bachelor-Arbeit-Thomas-Wichert/Assets/LoggerSkript.cs
2025-07-21 09:11:14 +02:00

99 lines
2.5 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class VRCameraLogger : MonoBehaviour
{
public Transform vrCamera; // Ziehen Sie hier Ihr VRCamera-Objekt im Inspector hinein
public float logInterval = 1.0f; // 1 Sekunde Intervall
private List<string> positionLogs = new List<string>();
private bool isLogging = true;
private string directoryPath;
private string filePath;
private void Start()
{
if (vrCamera == null)
{
Debug.LogError("VR Camera Transform is not assigned.");
return;
}
directoryPath = Path.Combine(Application.dataPath, "Datensammlung");
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
filePath = GenerateFilePath();
StartCoroutine(LogPosition());
}
private IEnumerator LogPosition()
{
while (isLogging)
{
yield return new WaitForSeconds(logInterval);
Vector3 position = vrCamera.position;
string logEntry = $"{position.x}:{position.y}:{position.z}";
positionLogs.Add(logEntry);
Debug.Log($"Logged Position: {logEntry}");
}
}
private void OnApplicationQuit()
{
Debug.Log("Application quitting, writing logs to file.");
isLogging = false;
WriteLogsToFile();
}
private void OnDisable()
{
// Zusätzlicher Schutz, falls OnApplicationQuit nicht ausgelöst wird
Debug.Log("Application is being disabled, writing logs to file.");
isLogging = false;
WriteLogsToFile();
}
private string GenerateFilePath()
{
int fileIndex = 0;
string path;
do
{
path = Path.Combine(directoryPath, $"daten{fileIndex:D2}.txt");
fileIndex++;
} while (File.Exists(path));
return path;
}
private void WriteLogsToFile()
{
string logData = string.Join("::", positionLogs);
try
{
File.WriteAllText(filePath, logData + "\n");
Debug.Log($"Logs written to {filePath}");
#if UNITY_EDITOR
AssetDatabase.Refresh(); // Erzwingen Sie eine Aktualisierung der Asset-Datenbank im Editor
#endif
}
catch (IOException e)
{
Debug.LogError($"Failed to write logs to file: {e.Message}");
}
}
}