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!

3 Answers

3

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.

Use Unique Name with GUID Generating like

"file-" + System.Guid.NewGuid() + ".wav"

to save file without checking for existing one.

AssetDatabase.GenerateUniqueAssetPath helped me

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.