I am fresh to C# (I do programm in other languages) and I got a task to record the position and rotation of an object inside Unity3D game.
I successfully created code that prints in Unity console current position and rotation with set timing (parts of void RecPoint without "lista"), and that at the end it saves all of the position data in one file (void SaveToFile).
What I wanted to do is to create one file for saving both position and rotation at the same time that looks like:
xposition; yposition; zposition; wrotation; xrotation; yrotation; zrotation
xposition; yposition; zposition; wrotation; xrotation; yrotation; zrotation
I wanted to achieve this by creating empty string list at the void Start and then adding position and rotation one step at the time (in void RecPoint). After that I would modify void SaveToFile to save everything simmiliar to what is currently in void SaveToFile.
The problem is that no matter if I use var lista = new List();
or
lista = new List();
I get the same error CS0103 with the only difference being that when used var lista I don't get the CS0103 error for this line.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReadData : MonoBehaviour
{
public string fileName = "D:/position.txt";
public List<Vector3> positions;
public List<Quaternion> rotations;
public float interval = 0.2f;
public float tSample = 1.0f;
void Start() {
positions = new List<Vector3>();
rotations = new List<Quaternion>();
var lista = new List<string>();
InvokeRepeating("RecPoint", tSample, interval);
}
void RecPoint()
{
positions.Add(transform.position);
rotations.Add(transform.rotation);
lista.Add(transform.position.ToString());
lista.Add(transform.rotation.ToString());
Debug.Log("position " transform.position " rotation " transform.rotation);
}
void SaveToFile(string fileName)
{
foreach (Vector3 pos in positions)
{
string line = System.String.Format("{0,3:f2};{1,3:f2};{2,3:f2}\r\n", pos.x, pos.y, pos.z);
System.IO.File.AppendAllText(fileName, line);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.O))
{
CancelInvoke("RecPoint");
SaveToFile(fileName);
Debug.Log("Koniec czytania danych, zapisuję do pliku");
}
}
}
CodePudding user response:
Well the problem is that you did not define the List "lista" anywhere.
Declare like so : public List<string> lista;
And then in Start() do : lista = new List<string>();
You can compress all of this into one line when declaring, like so : public List<string> lista = new List<string>();
Hope it helped!