C# 每次脚本被称为C时增量文件#
我从unity项目中调用此脚本。在这一点上,我试图做的是在每次调用脚本时递增文件 因此,一旦调用它,它将读取数据并将数据保存在文件中 现在它只生成一个文件C# 每次脚本被称为C时增量文件#,c#,unity3d,arduino,serial-port,C#,Unity3d,Arduino,Serial Port,我从unity项目中调用此脚本。在这一点上,我试图做的是在每次调用脚本时递增文件 因此,一旦调用它,它将读取数据并将数据保存在文件中 现在它只生成一个文件alpha0.csv,如果我再次调用脚本,它不会打印新文件 有谁能指导我如何解决这个问题吗 using UnityEngine; using System; using System.Collections; using System.IO.Ports; using System.IO; using System.Management; usi
alpha0.csv
,如果我再次调用脚本,它不会打印新文件
有谁能指导我如何解决这个问题吗
using UnityEngine;
using System;
using System.Collections;
using System.IO.Ports;
using System.IO;
using System.Management;
using Microsoft.Win32;
using System.Collections.Generic;
public class ArduinoControl : MonoBehaviour
{
SerialPort arduino;
public string portName = "COM5";
public static bool status ;
public string test = "alpha";
private static int counter;
private static int lineCount;
private static string receivedstring = string.Empty;
void Start()
{
arduino = new SerialPort(portName, 115200);
arduino.Open();
status = true;
}
void Update()
{
if (arduino.IsOpen)
{
if (status) // (& UnityCommand = "F")
{
arduino.Write("s");
arduino.ReadTimeout = 5000;
arduino.WriteTimeout = 5000;
receivedstring += arduino.ReadLine() + "\r\n";
arduino.BaseStream.Flush();
lineCount++;
if(lineCount >= 10 && receivedstring != null)
{
WriteOutputToTextFile(test,receivedstring); // Write to csv here...
status = false;
}
arduino.BaseStream.Flush();
}
}
}
//private static int counter;
static void WriteOutputToTextFile(string path,string _data)
{
string FolderName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //set destination as your desktop
using (StreamWriter SW = new StreamWriter($"{FolderName }\\{path}{counter}.csv", false))
{
SW.WriteLine(_data);
SW.Close();
}
counter++;
lineCount = 0;
receivedstring = string.Empty;
}
}
如果我理解正确,您希望使用正确的数字后缀创建一个新文件,如
alpha0.csv
,alpha1.csv
,alpha2.csv
。。。
这实际上可能有点麻烦,您可以像评论所建议的那样在更大范围内使用变量,但当您将其保存到磁盘时,我假设您希望它在启动和停止程序之间正常工作
我建议
可以在Unity中读取文件名,如下所示:
DirectoryInfo dir = new DirectoryInfo("/*your directory*/");
FileInfo[] fileInfos = dir.GetFiles("*.csv");
然后获取下一个后缀
static readonly string rootName = "Alpha";
int maxFileNumber = 0;
foreach (var f in fileInfos)
{
string tempName = f.Name;
tempName = tempName.Substring(0, tempName.Length - ".csv".Length); // remove .csv
int lengthOfNumber = tempName.Length - rootName.Length; // get the length of the number at the end of the name
nextFileNumber = int.Parse(tempName.Substring(rootName.Length, lengthOfNumber)); // get the number at the end of the name
maxFileNumber = nextFileNumber > maxFileNumber ? nextRoomNumber : maxRoomNumber; // find max alorithm
}
nextFileNumber += 1; // next number
string newFileName = rootName + ToString(nextFileNumber)+".csv";
你的意思是再次“调用脚本”整个发布的程序吗?如果是这样,var计数器是本地定义的,那么每次调用它时,它都以0开始。您需要在调用/main程序中使用全局变量,或者您计算dir中的文件数,并将计数器设置为_dir+1中下一个最大的文件数_,您能否在此场景中为我提供一个示例main函数?如果我要使用当前代码执行此操作,您能告诉我如何执行此操作吗?编辑以更好地解释,希望这有帮助