- Home /
Incremental Filename if it exists
Hi all,
I have the following code:
using UnityEngine;
public class audioRec : MonoBehaviour
{
AudioClip myAudioClip;
void Start() {}
void Update () {}
void OnGUI()
{
if (GUI.Button(new Rect(10,10,60,50),"Record"))
{
myAudioClip = Microphone.Start ( null, false, 10, 44100 );
}
if (GUI.Button(new Rect(10,70,60,50),"Save"))
{
SavWav.Save("myfile", myAudioClip);
// audio.Play();
}
}
}
I need to see if the file exists and add an incremental number after if it does (ie myfile0001, myfile0002, etc)
I should need something like this, but I can't figure it out:
if (File.Exists(myfile))
{
fileName = myfile + "(" + count.ToString() + ");
count++;
}
else
{
SavWav.Save(myfile);
}
HELP!
Thank you!
Update:
I have gotten this far
using UnityEngine;
public class audioRec_variable : $$anonymous$$onoBehaviour
{
AudioClip myAudioClip;
void Start() {}
void Update () {}
void OnGUI()
{
if (GUI.Button(new Rect(10,10,60,50),"Record"))
{
myAudioClip = $$anonymous$$icrophone.Start ( null, false, 10, 44100 );
}
if (GUI.Button(new Rect(10,70,60,50),"Save"))
{
for (int i = 1; ;i++)
if (System.IO.File.Exists("myfile"))
{
SavWav.Save("myfile" + i, myAudioClip);
}
else
{
SavWav.Save("myfile", myAudioClip);
// audio.Play();
}
}
}
}
Answer by Graham-Dunnett · Mar 04, 2013 at 11:28 AM
You need to also check that the filename you compute (myfile1, myfile2, etc) don't also exist. So, use Exists
inside you loop with the filenames you compute. When Exists
returns False
then you know you have a filename that is new.
Answer by makaka-org · Apr 10, 2020 at 10:45 PM
Use Unique Name with GUID Generating like
"file-" + System.Guid.NewGuid() + ".wav"
to save file without checking for existing one.
Answer by najati · Jul 28, 2021 at 12:43 PM
AssetDatabase.GenerateUniqueAssetPath helped me
https://docs.unity3d.com/ScriptReference/AssetDatabase.GenerateUniqueAssetPath.html
When you call this method, Unity checks to see whether an asset already exists with the matching path and filename you supply. If it does not exist, Unity returns the same string you supplied. If there is already an existing asset with the matching path and filename, Unity appends the number 1 to the filename and checks again.
Your answer
Follow this Question
Related Questions
Does Unity have an equivalent to browser cookies or Flash sharedObjects to save data? 1 Answer
How do I access music files on the Oculus Quest and play them? 0 Answers
Is accessing user documents folder possible on Unity3D? 0 Answers
What is the best way to save a modified texture to disk? 1 Answer
How to tell android to open a file 0 Answers