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

101 lines
2.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class VRCameraLoggerV2 : MonoBehaviour
{
public Transform vrCamera; // Ziehen Sie hier Ihr VRCamera-Objekt im Inspector hinein
public float logInterval = 0.1f; // 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;
Vector3 rotation = vrCamera.eulerAngles;
string logEntry = $"{position.x}:{position.y}:{position.z}-{rotation.x}:{rotation.y}:{rotation.z};";
positionLogs.Add(logEntry);
Debug.Log($"Logged Position and Rotation: {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("\n", 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}");
}
}
}