Skip to content

Commit e6a5fc3

Browse files
committed
added function to increment filename if it already exists
1 parent 329cfd3 commit e6a5fc3

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

Assets/FbxExporters/Editor/ConvertToModel.cs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,11 @@ private static List<GameObject> OnConvertInPlace (GameObject [] unityActiveGOs)
7676
string dirPath = Path.Combine (Application.dataPath, "Objects");
7777

7878
for(int n = 0; n < gosToExport.Length; n++){
79-
filePaths[n] = Path.Combine (dirPath, gosToExport[n].name + ".fbx");
79+
var filename = gosToExport [n].name + ".fbx";
80+
if (File.Exists (Path.Combine(dirPath, filename))) {
81+
filename = IncrementFileName (dirPath, filename);
82+
}
83+
filePaths[n] = Path.Combine (dirPath, filename);
8084
}
8185

8286
string[] fbxFileNames = new string[filePaths.Length];
@@ -136,6 +140,37 @@ private static List<GameObject> OnConvertInPlace (GameObject [] unityActiveGOs)
136140
return result;
137141
}
138142

143+
/// <summary>
144+
/// Check if the file exists, and if it does, then increment the name.
145+
/// e.g. if filename is Sphere.fbx and it already exists, change it to Sphere1.fbx.
146+
/// </summary>
147+
/// <returns>new file name.</returns>
148+
/// <param name="filename">Filename.</param>
149+
private static string IncrementFileName(string path, string filename)
150+
{
151+
string fileWithoutExt = Path.GetFileNameWithoutExtension (filename);
152+
string ext = Path.GetExtension (filename);
153+
string pattern = string.Format (@"{0}{1}{2}", fileWithoutExt, "*", ext);
154+
string[] files = Directory.GetFiles (path, pattern, SearchOption.TopDirectoryOnly);
155+
156+
int index = 0;
157+
string groupName = "index";
158+
pattern = string.Format (@"{0}{1}\{2}", fileWithoutExt, "[ ]*(?<"+groupName+">[0-9]*?)", ext);
159+
foreach (var file in files) {
160+
var match = System.Text.RegularExpressions.Regex.Match (file, pattern);
161+
if (match.Success) {
162+
string indexMatch = match.Groups [groupName].Value;
163+
if (!string.IsNullOrEmpty(indexMatch)) {
164+
int i = -1;
165+
if (int.TryParse (indexMatch, out i) && i > index) {
166+
index = i;
167+
}
168+
}
169+
}
170+
}
171+
return string.Format ("{0} {1}{2}", fileWithoutExt, (index + 1), ext);
172+
}
173+
139174
private static void SetupImportedGameObject(GameObject orig, GameObject imported)
140175
{
141176
Transform importedTransform = imported.transform;

0 commit comments

Comments
 (0)