Hey there,
I’m new to Unity and Coding in C# and thus try to learn as much as possible as I go. For a project at uni I have to log the movements of the player in a 3D environment. I tried to modify an already existing C#-script (since I don’t think I’d be able to come up with something like this on my own) but I have encountered a problem: the code runs without a Debug-Error-Message and creates a directory, but afterwards no file is created…
Honestly, I don’t know why. I would greatly appreciate if someone could take a look at this script. Maybe you are able to see something that my “beginner’s eyes” can’t.
Thanks a lot,
Lukas
using System.IO;
using System;
using System.Collections.Generic;
public class Log : MonoBehaviour
{
public TextWriter fs;
public GameObject playerobject;
public Vector3 playerlocation;
public bool PositionLogging = true;
bool is_logging = false;
float deltaTime = 0.1f; // every 100ms
float timeToLog;
public void StartLogging ()
{
playerobject = GameObject.Find ("RigidBodyFPSController");
playerlocation = playerobject.transform.position;
if (is_logging) return;
if (!Directory.Exists(@".\logs"))
Directory.CreateDirectory(@".\logs");
var nameOfLogFile = (System.DateTime.Now+"")+ "_log.csv";
this.fs = new StreamWriter(Path.Combine("./logs",nameOfLogFile), true){AutoFlush = true};
this.fs.WriteLine("#Time is| " + System.DateTime.Now.ToLongTimeString() +" "+ System.DateTime.Now.ToLongDateString() );
this.fs.WriteLine("#logged object is | " + this.name);
this.fs.WriteLine("#Format is | time (sec since program start)| name of object logged| x|y|z|");
is_logging = true;
}
void Start ()
{
if (!Directory.Exists(@".\logs"))
Directory.CreateDirectory(@".\logs");
}
void Update()
{
if (!is_logging || Time.time < timeToLog || !PositionLogging) return;
timeToLog = Time.time + deltaTime;
fs.Write(String.Format("{0:0.0000000}|", Time.time));
fs.Write(LoggTransform(playerobject));
//foreach(ILoggable l in this.loggables) if(l.Logg()) fs.Write(l.ToLogg());
fs.Write(Environment.NewLine);
}
private string LoggTransform (GameObject playerobject)
{
return String.Format("{1:0.0000}|{2:0.0000}|{3:0.0000}|",
playerobject.gameObject.name,
playerobject.transform.position.x,
playerobject.transform.position.y,
playerobject.transform.position.z
);
}
}