FishPlayer

一个喜欢摸鱼的废物

0%

查询Asset在工程中的引用(GUID)

之前我用Unity自带的API去查询一些物体的引用,结果当然是超超超超超级慢,对于那些把项目工程放在辣鸡机械盘上的同事,这个工具根本是没法好好用的。而且因为要用Unity的APi,自然是没办法使用async的。

最近导师拿到QA那边提供的一个类似的工具,改了一下,做了一个超级快的版本。

思路

思路其实是非常简单的。我们知道Unity Asset会有一个唯一的GUID,那我们就可以用这个GUID去查询其引用。
查询的时候我们也不需要使用Unity API去检查引用,而是把我们的各种Asset都当成文本文件直接读取,然后直接在这些文本里去匹配我们需要查询的GUID。

代码

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
387
388
389

// Analyze asset as text file

public interface IFileAnalysis<T>
{
public int FileCount { get; }
public int Scanned { get; }
public Task<T> Task { get; }
public float PercentCompletion { get; }
public string CurrentOperationMessage { get; }
public bool Running { get; }
public void Cancel();
}

public static class FileAnalyzer
{
public class FileAnalysis<T> : IFileAnalysis<T>
{
CancellationTokenSource m_tokenSource = new CancellationTokenSource
public Task<T> Task { get; set; }
public float PercentCompletion { get; set; }
public string CurrentOperationMessage { get; set; }
public int FileCount { get; set; }
public int Scanned { get; set; }
public bool Running => Task.Status switch
{
TaskStatus.RanToCompletion => false,
TaskStatus.Faulted => false,
TaskStatus.Canceled => false,
_ => true
};
public CancellationToken Token => m_tokenSource.Token
public void Cancel()
{
m_tokenSource.Cancel();
}
}

public static IFileAnalysis<string[]> AnalyzeFolders(string[] folders, System.Predicate<string> fileFilter, Regex content)
{
FileAnalysis<string[]> operation = new FileAnalysis<string[]>();
operation.Task = Task.Factory.StartNew<string[]>(() => CheckFolders(folders, fileFilter, content, operation), TaskCreationOptions.LongRunning);
return operation;
}

private static string[] CheckFolders(string[] folders, System.Predicate<string> fileFilter, Regex fileContent, FileAnalysis<string[]> operationStatus)
{
string[] files = folders.SelectMany(folder => Directory.GetFiles(folder, "*", SearchOption.AllDirectories)).ToArray();
List<string> result = new List<string>(200);
int count = files.Length;
operationStatus.FileCount = count;
operationStatus.Scanned = 0;
operationStatus.PercentCompletion = 0f;
for (int i = 0; i < count; i++)
{
operationStatus.Token.ThrowIfCancellationRequested();
string filePath = files[i];
if (fileFilter(filePath))
{
operationStatus.CurrentOperationMessage = filePath;
if (CheckFile(filePath, fileContent))
{
result.Add(filePath);
}
operationStatus.Scanned++;
operationStatus.PercentCompletion = (i / (float)count) * 100f;
}
}
return result.ToArray();
}

private static bool CheckFile(string filepath, Regex fileContent)
{
string assetText = File.ReadAllText(filepath);
MatchCollection matches = fileContent.Matches(assetText);
bool result = matches.Count > 0;
return result;
}
}

// Editor window

public class AssetUsageSearchWindow : EditorWindow
{
[Flags]
private enum AssetFilter
{
Asset = 1 << 0,
Material = 1 << 1,
Prefab = 1 << 2,
Scene = 1 << 3
}

[Serializable]
private struct SearchRequest
{
public bool searchTextOnly;
public string targetString
public UnityObject Asset
{
get
{
string path = AssetPath;
if (string.IsNullOrEmpty(path))
{
return null;
}
return AssetDatabase.LoadAssetAtPath<UnityObject>(path);
}
set
{
if (null != value && AssetDatabase.TryGetGUIDAndLocalFileIdentifier<UnityObject>(value, out string guid, out _))
{
targetString = guid;
}
}
}

public string AssetPath => searchTextOnly ? string.Empty : AssetDatabase.GUIDToAssetPath(targetString
public long FileID
{
get
{
UnityObject asset = Asset;
if (null != asset && AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out _, out long fileId))
{
return fileId;
}
return 0;
}
}
}

[System.Serializable]
private struct SearchResult
{
public string path;
public UnityObject asset;
/// <summary>
/// used to ping the actual asset dat has the direct reference
/// </summary>
public UnityObject subAssetIfNeed;
}

/// <summary>
/// only search specify text from asset
/// </summary>
private bool m_searchTextOnly = false;
private AssetFilter m_filter = (AssetFilter)~0; // Everything by default
private List<string> m_searchFolders = new List<string>();
private SearchRequest m_search;

private IFileAnalysis<string[]> m_findTask = null;
private bool m_waitForResult = false;
private SearchResult[] m_findResults = null;
private Regex m_pathFilterRegex;

private Vector2 m_scrollPos;
private Stopwatch m_processTime;

private bool IsBusy => null != m_findTask && m_findTask.Running;

[MenuItem("Muy Tools/Asset Usage Search", priority = 4)]
private static void Init()
{
AssetUsageSearchWindow window = CreateWindow<AssetUsageSearchWindow>();
window.Show();
window.titleContent = new GUIContent("Asset Usage Search");
}

private void OnGUI()
{
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
// switch search mode
m_searchTextOnly = EditorGUILayout.Toggle("Search Text Only", m_searchTextOnly
// draw search info
string searchLable = m_searchTextOnly ? "Search for string (Text)" : "Search for Asset (GUID)";
SearchRequest request = m_search;
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel(searchLable);
if (m_searchTextOnly)
{
request.targetString = EditorGUILayout.TextField(request.targetString);
}
else
{
GUI.enabled = false;
request.targetString = EditorGUILayout.TextField(request.targetString);
GUI.enabled = true;
request.Asset = EditorGUILayout.ObjectField(request.Asset, typeof(UnityObject), false);
using (new EditorGUI.DisabledGroupScope(true))
{
EditorGUILayout.TextField("FileID: ", request.FileID.ToString());
}
}
}
m_search = request
m_filter = (AssetFilter)EditorGUILayout.EnumFlagsField("Search Filter", m_filter);
EditorGUILayout.LabelField("Search folders:");
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
for (int i = 0; i < m_searchFolders.Count; i++)
{
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(26)))
{
m_searchFolders.RemoveAt(i);
i--;
continue;
}
string folderResult = DrawSelectFolder(m_searchFolders[i]);
m_searchFolders[i] = string.IsNullOrEmpty(folderResult) ? m_searchFolders[i] : folderResult;
}

if (GUILayout.Button("Add Folder"))
{
m_searchFolders.Add(Application.dataPath);
}
}
}

// search button
using (new EditorGUI.DisabledGroupScope(IsBusy))
{
if (GUILayout.Button($"Search References for {m_search.targetString}"))
{
if (!string.IsNullOrEmpty(m_search.targetString))
{
DoFind();
}
}

bool isSearching = null != m_findTask && m_findTask.Task.Status == TaskStatus.Running;
bool isFaulted = null != m_findTask && m_findTask.Task.Status == TaskStatus.Faulted
if (isSearching) SearchingGUI();
else if (isFaulted) EditorGUILayout.HelpBox($"Error while running search:\n{m_findTask.Task.Exception}", MessageType.Error);
else if (m_findResults != null) SearchResultGUI();
}

private string DrawSelectFolder(string folderPath)
{
using (new EditorGUILayout.HorizontalScope())
{
GUI.enabled = false;
EditorGUILayout.TextField(folderPath);
GUI.enabled = true;
if (GUILayout.Button("Select"))
{
folderPath = EditorUtility.OpenFolderPanel("Select search folder", Application.dataPath, "");
}
}
return folderPath;
}

private void DoFind()
{
m_findResults = null;
m_waitForResult = true;
m_processTime = Stopwatch.StartNew();
RefreshPathFilter();
m_findTask = FileAnalyzer.AnalyzeFolders(m_searchFolders.Count > 0 ? m_searchFolders.ToArray() : new string[] { Application.dataPath }, FilterPath, new Regex(m_search.targetString));
m_findTask.Task.ContinueWith(task =>
{
if (task.Status == TaskStatus.RanToCompletion)
{
string[] result = task.Result;
}
});
}

private bool FilterPath(string path)
{
if (null == m_pathFilterRegex)
{
return false;
}
return m_pathFilterRegex.IsMatch(path);
}

private void SearchingGUI()
{
EditorGUILayout.LabelField($"Searching: {m_findTask.PercentCompletion}%");
EditorGUILayout.LabelField(m_findTask.CurrentOperationMessage);
if (GUILayout.Button("Cancel"))
{
m_findTask.Cancel();
m_findTask = null;
}

private void SearchResultGUI()
{
EditorGUILayout.LabelField($"Found {m_findResults.Length} assets:");
if (null != m_processTime)
{
m_processTime.Stop();
EditorGUILayout.LabelField($"Search time {m_processTime.ElapsedMilliseconds}ms, {m_findTask.Scanned}/{m_findTask.FileCount} files scanned");
}
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Copy list to clipboard", EditorStyles.miniButton))
{
GUIUtility.systemCopyBuffer = string.Join("\n", m_findResults.Select(rst => rst.path));
}
GUILayout.FlexibleSpace();
}
// since we dun have tons of result, we dun need to apply recycle scroll view here
using (EditorGUILayout.ScrollViewScope scrollview = new EditorGUILayout.ScrollViewScope(m_scrollPos, EditorStyles.helpBox))
{
m_scrollPos = scrollview.scrollPosition;
using (new EditorGUILayout.VerticalScope())
{
for (int i = 0; i < m_findResults.Length; i++)
{
using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox))
{
SearchResult result = m_findResults[i];
Rect foldoutRect = GUILayoutUtility.GetRect(20, EditorGUIUtility.singleLineHeight, GUILayout.Width(20));
EditorGUILayout.ObjectField(result.asset, typeof(UnityObject), false);
EditorGUILayout.LabelField(new GUIContent(result.path, result.path));
m_findResults[i] = result;
EditorGUILayout.EndFoldoutHeaderGroup();
}
}
}
}
}

private void Update()
{
if (null != m_findTask)
{
if (m_findTask.Task.Status == TaskStatus.Running)
{
Repaint();
}
else if (m_findTask.Task.Status == TaskStatus.RanToCompletion && m_waitForResult)
{
// Result filling is done here because it needs to run on main thread
m_waitForResult = false;
string[] result = m_findTask.Task.Result;
int count = result.Length;
m_findResults = new SearchResult[count];
for (int i = 0; i < count; i++)
{
string assetPath = $"Assets{result[i].Substring(Application.dataPath.Length)}";
UnityObject asset = AssetDatabase.LoadAssetAtPath<UnityObject>(assetPath);
m_findResults[i] = new SearchResult
{
path = result[i],
asset = asset,
};
}
Repaint();
}
}
}

private void RefreshPathFilter()
{
string extensionFilter = GetExtensionFilter(m_filter);
m_pathFilterRegex = new Regex(string.Format(@"^.*\.({0})$", extensionFilter));
}

private string GetExtensionFilter(AssetFilter filter)
{
List<string> extensions = new List<string>();
if (filter.HasFlag(AssetFilter.Asset))
{
extensions.Add("asset");
}
if (filter.HasFlag(AssetFilter.Material))
{
extensions.Add("mat");
}
if (filter.HasFlag(AssetFilter.Prefab))
{
extensions.Add("prefab");
}
if (filter.HasFlag(AssetFilter.Scene))
{
extensions.Add("unity");
}
string extensionFilter = string.Join("|", extensions);
return extensionFilter;
}
}

关键代码和Unity API毫无关系,可以避免长时间的卡死,而且我们也能加入取消搜索的功能之类的。如果在乎性能的话可以还可以在读文件检查这边做优化。不过感觉这样已经比之前快了许多了。