-
Notifications
You must be signed in to change notification settings - Fork 0
/
Instancer.cs
386 lines (336 loc) · 12 KB
/
Instancer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace VRLabs.Instancer
{
[InitializeOnLoad]
public class Instancer : MonoBehaviour
{
static bool renameInstances;
static Instancer()
{
renameInstances = PlayerPrefs.GetString("VRLabs.Instancer.RenameInstances", "False") == "True"; ;
}
[MenuItem("VRLabs/Rename new Instances", priority = 1)]
public static void RenameInstancesToggle()
{
renameInstances = !renameInstances;
PlayerPrefs.SetString("VRLabs.Instancer.RenameInstances", renameInstances.ToString());
}
[MenuItem("VRLabs/Rename new Instances", true)]
public static bool RenameInstancesToggleValidate()
{
Menu.SetChecked("VRLabs/Rename new Instances", renameInstances);
return true;
}
[MenuItem("VRLabs/Create Instance/Any Package")]
public static void CreateInstanceAnyPackageStart()
{
string sourceFolder = EditorUtility.OpenFolderPanel("Select Directory To Copy Assets From", "Assets/", "");
if (sourceFolder == "" || sourceFolder == null)
{
Debug.LogError("No folder selected, please select a folder to copy the assets to.");
return;
}
string targetFolder = EditorUtility.OpenFolderPanel("Select Directory To Copy Assets To", "Assets/", "");
if (targetFolder == "" || targetFolder == null)
{
Debug.LogError("No folder selected, please select a folder to copy the assets to.");
return;
}
if (!targetFolder.Contains(Application.dataPath))
{
Debug.LogError("Selected folder is not in the Assets folder, please select a folder in the Assets directory.");
return;
}
if (renameInstances)
{
EnterValueWindow.Open("", "Enter Old Package name", (oldName) =>
{
EnterValueWindow.Open(oldName, "Enter New Instance name", (newName) =>
{
FinishInstancing(oldName, "Assets" + sourceFolder.Replace(Application.dataPath, ""), new[]
{
".*\\.cs",
".*\\.asmdef",
".*\\.shader",
"package.json"
}, targetFolder, newName, null, true);
});
});
}
else
{
EnterValueWindow.Open("", "Enter New Instance name", (newName) =>
{
FinishInstancing(newName, "Assets" + sourceFolder.Replace(Application.dataPath, ""), new[]
{
".*\\.cs",
".*\\.asmdef",
".*\\.shader",
"package.json"
}, targetFolder, null, null, true);
});
}
}
public static void Instance(string packageName, string installFilePath, string[] excludeRegexs)
{
InstanceWithCallback(packageName, installFilePath, excludeRegexs, null);
}
// Done this way because existing packages call the Instance method with 3 parameters
public static void InstanceWithCallback(string packageName, string installFilePath, string[] excludeRegexs, Action<string> callBack = null)
{
string targetFolder = EditorUtility.OpenFolderPanel("Select Directory To Copy Assets To", "Assets/", "");
if (targetFolder == "" || targetFolder == null)
{
Debug.LogError("No folder selected, please select a folder to copy the assets to.");
return;
}
if (!targetFolder.Contains(Application.dataPath))
{
Debug.LogError("Selected folder is not in the Assets folder, please select a folder in the Assets directory.");
return;
}
if (renameInstances)
{
EnterValueWindow.Open(packageName, "Enter new Instance Name",(newName) => FinishInstancing(packageName, installFilePath, excludeRegexs, targetFolder, newName, callBack));
return;
}
FinishInstancing(packageName, installFilePath, excludeRegexs, targetFolder, callBack: callBack);
}
// Done this way because we need the unity editor to continue running during the rename popup window.
public static void FinishInstancing(string packageName, string installFilePath, string[] excludeRegexs,
string targetFolder, string newInstanceName = null, Action<string> callBack = null, bool isAnyPackage = false)
{
targetFolder = PrepareTargetFolderPath(targetFolder, newInstanceName != null ? newInstanceName : packageName);
string sourceFolder = isAnyPackage ? installFilePath : GetSourceFolder(installFilePath);
string[] localAssetPaths = GetLocalAssetPaths(sourceFolder, excludeRegexs);
CreateDirectories(localAssetPaths, targetFolder);
CopyFiles(localAssetPaths, sourceFolder, targetFolder);
AssetDatabase.Refresh();
FixReferences(localAssetPaths, sourceFolder, targetFolder);
if (newInstanceName != null)
{
RenameInstance(localAssetPaths, targetFolder, packageName, newInstanceName);
}
AssetDatabase.Refresh();
callBack?.Invoke(targetFolder);
}
static string PrepareTargetFolderPath(string folderPath, string packageName)
{
folderPath = "Assets" + folderPath.Remove(0, Application.dataPath.Length) + "/" + packageName;
if (Directory.Exists(folderPath))
{
int i = 1;
while (Directory.Exists(folderPath + i.ToString()))
{
i++;
}
folderPath += i;
}
Directory.CreateDirectory(folderPath);
AssetDatabase.ImportAsset(folderPath);
return folderPath;
}
static string GetSourceFolder(string installFilePath)
{
string sourceFolder = installFilePath;
#if UNITY_2019
while (!File.Exists("." + sourceFolder + "/package.json"))
#else
if (sourceFolder.StartsWith("/Assets")) sourceFolder = sourceFolder.Replace("/Assets", "./Assets");
while (!File.Exists(sourceFolder + "/package.json"))
#endif
{
if (sourceFolder == null)
{
throw new ArgumentException("Supplied path not in correct format");
}
sourceFolder = Path.GetDirectoryName(sourceFolder);
}
#if UNITY_2019
return sourceFolder.Replace("\\", "/").Substring(1);
#else
return sourceFolder.Replace("\\", "/").Substring(2);
#endif
}
static string[] GetLocalAssetPaths(string sourceFolder, string[] excludeRegexs)
{
string[] assetPaths = AssetDatabase.FindAssets("", new [] { sourceFolder }).Select(AssetDatabase.GUIDToAssetPath).ToArray();
string[] filteredLocalAssetPaths = assetPaths
.Select(path => path.Remove(0,sourceFolder.Length))
.Where(path => excludeRegexs.All(regex => !Regex.Match(path, regex).Success))
.ToArray();
return filteredLocalAssetPaths;
}
static void CreateDirectories(string[] filePaths, string targetFolder)
{
try
{
AssetDatabase.StartAssetEditing();
foreach (string path in filePaths)
{
string targetPath = Path.GetDirectoryName(targetFolder + path);
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
AssetDatabase.ImportAsset(targetPath);
}
}
}
finally
{
AssetDatabase.StopAssetEditing();
}
}
static void CopyFiles(string[] filePaths, string sourceFolder, string targetFolder)
{
try
{
AssetDatabase.StartAssetEditing();
foreach (string path in filePaths)
{
if (!Directory.Exists(sourceFolder + path))
{
AssetDatabase.CopyAsset(sourceFolder + path, targetFolder + path);
}
}
}
finally{
AssetDatabase.StopAssetEditing();
}
}
static void FixReferences(string[] localAssetPaths, string sourceFolder, string targetFolder)
{
foreach (string localAssetPath in localAssetPaths)
{
string targetAssetPath = targetFolder + localAssetPath;
UnityEngine.Object[] targetAssets = AssetDatabase.LoadAllAssetsAtPath(targetAssetPath).Where(x => x != null).ToArray();
foreach (var targetAsset in targetAssets)
{
SerializedObject serializedObject = new SerializedObject(targetAsset);
SerializedProperty property = serializedObject.GetIterator();
bool changed = false;
bool newChanged = false;
do
{
if (property.propertyPath.Contains("m_Modification")) continue;
if (property.propertyType == SerializedPropertyType.ObjectReference)
{
if (property.objectReferenceValue != null)
{
Object newObject;
(newObject, newChanged) = GetTargetVersion(sourceFolder, targetFolder, property.objectReferenceValue);
if (newChanged)
{
changed = true;
property.objectReferenceValue = newObject;
}
}
}
if (property.propertyType == SerializedPropertyType.ExposedReference)
{
if (property.exposedReferenceValue != null)
{
Object newObject;
(newObject, newChanged) = GetTargetVersion(sourceFolder, targetFolder, property.exposedReferenceValue);
if (newChanged)
{
changed = true;
property.exposedReferenceValue = newObject;
}
}
}
} while (property.Next(true));
if (changed) serializedObject.ApplyModifiedProperties();
}
}
}
static void RenameInstance(string[] localAssetPaths, string targetFolder, string packageName, string newInstanceName)
{
foreach (string localAssetPath in localAssetPaths)
{
string targetAssetPath = targetFolder + localAssetPath;
UnityEngine.Object[] targetAssets = AssetDatabase.LoadAllAssetsAtPath(targetAssetPath).Where(x => x != null).ToArray();
if (targetAssets.Length == 0) continue;
string[] possibleNames = new []{packageName, packageName.Replace("-", ""), packageName.Replace("-", " ")};
foreach (var targetAsset in targetAssets)
{
SerializedObject serializedObject = new SerializedObject(targetAsset);
SerializedProperty property = serializedObject.GetIterator();
do
{
if (property.propertyPath.Contains("m_Modification")) continue;
if (property.propertyType == SerializedPropertyType.String)
{
string value = property.stringValue;
if (value == null) continue;
foreach (string possibleName in possibleNames)
{
if (value.StartsWith(possibleName) && !value.StartsWith(newInstanceName))
{
property.stringValue = ReplaceAtStart(value, possibleName, newInstanceName);
break;
}
}
}
} while (property.Next(true));
serializedObject.ApplyModifiedProperties();
}
String fileName = Path.GetFileName(targetAssetPath);
foreach (string possibleName in possibleNames)
{
if (fileName.StartsWith(possibleName))
{
fileName = ReplaceAtStart(fileName, possibleName, newInstanceName);
AssetDatabase.RenameAsset(targetAssetPath, fileName);
break;
}
}
}
}
public static string ReplaceAtStart(string str, string oldValue, string newValue)
{
return newValue + str.Substring(oldValue.Length);
}
private static (Object, bool) GetTargetVersion(string sourceFolder, string targetFolder, Object target)
{
string targetPath = AssetDatabase.GetAssetPath(target);
if (targetPath.StartsWith(sourceFolder))
{
string newTargetPath = targetFolder + targetPath.Remove(0, sourceFolder.Length);
Object newObject = AssetDatabase.LoadAllAssetsAtPath(newTargetPath).Where(obj => obj.GetType() == target.GetType()).FirstOrDefault(x => x.name == target.name);
return (newObject, newObject != null);
}
return (target, false);
}
}
public class EnterValueWindow : EditorWindow
{
private string value = "";
private string windowTitle;
private Action<string> callBack;
public static void Open(string packageName, string windowTitle, Action<string> callBack)
{
var window = GetWindow<EnterValueWindow>(windowTitle);
window.windowTitle = windowTitle;
window.value = packageName;
window.callBack = callBack;
window.Show();
}
private void OnGUI()
{
EditorGUILayout.LabelField(windowTitle, EditorStyles.boldLabel);
value = EditorGUILayout.TextField(value);
if (GUILayout.Button("Submit"))
{
Close();
callBack(value);
}
}
}
}