1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using UnityEngine;
- using UnityEngine.AI;
- using System;
- using System.IO;
- public class WriteInCSVNew : MonoBehaviour
- {
- [Header("File Index:")]
- public int index = 0;
- [Header("Start Time:")]
- public float startTime = 0f;
- private string path;
- private float time = 0f;
- private float stopTime = 0f;
- private GameObject[][] humansGO;
- private NavMeshAgent[][] humansNMA;
- private void Start()
- {
- humansGO = gameObject.GetComponent<InstantiatePrefab>().humanGameObject;
- humansNMA = gameObject.GetComponent<InstantiatePrefab>().humanNavMeshAgent;
- string currentPath = Directory.GetCurrentDirectory();
- string reference = @"\Assets\Data_position\";
- string directory = currentPath + @"\Assets\Data_position";
- // create directory if not existing
- if (!Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- // create file for path
- using (File.Create(currentPath + reference + "Walk" + index + ".csv"))
- {
- path = currentPath + reference + "Walk" + index + ".csv";
- }
- // write column name
- using (StreamWriter firstLine = new StreamWriter(path))
- {
- var line = string.Format("Delta Time;Human i;Human j;Position x;Position y;Position z;Rotation x;Rotation y;Rotation z;Rotation w;Speed");
- firstLine.WriteLine(line);
- firstLine.Flush();
- }
- }
- // Start is called before the first frame update
- private void FixedUpdate()
- {
- if(stopTime >= startTime)
- {
- if (File.Exists(path))
- {
- try
- {
- using (StreamWriter file = new StreamWriter(path, true))
- {
- for(int i = 0; i < humansGO.Length; i++)
- {
- for(int j = 0; j < humansGO[i].Length; j++)
- {
- // Save position of Human leaders in file
- Vector3 pos = humansGO[i][j].transform.position; // (x,y,z)
- Quaternion rot = humansGO[i][j].transform.rotation; // (x,y,z,w)
- float speed = humansNMA[i][j].velocity.magnitude;
- var line = string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9};{10}",
- time, i, j, pos.x.ToString("f6"), pos.y.ToString("f6"), pos.z.ToString("f6"), rot.x.ToString("f6"), rot.y.ToString("f6"), rot.z.ToString("f6"), rot.w.ToString("f6"), speed);
- file.WriteLine(line);
- file.Flush();
- }
- }
- }
- }
- catch (Exception e)
- {
- throw new ApplicationException("Something went wrong by writing into a csv file: ", e);
- }
- }
- time += Time.deltaTime;
- }
- else
- stopTime += Time.deltaTime;
- }
- }
|