FishPlayer

一个喜欢摸鱼的废物

0%

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

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

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

思路

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

特殊用途

最近给项目里导入了一些新的UI组件,其中包含一个继承TMP后拓展的好用的UXTMP(继承于TMP)。交互那边提了个需求是要求把当前UI Prefab里所有的TMP换成UXTMP。没想到这个时候我们的这个工具又有了大用了。
我们用文本的方式打开prefab,然年后找到对应节点里的这一行 m_Script: {fileID: xxxxxxxx, guid: f46886236gsd6437aeb418b961at14c5, type: 3} 把guid改成UXTMP的guid就好了,详情参考着一篇笔记。这一行是描述某个组件对应的类的类型。既然UXTMP继承自TMP,那我们也不需要调整序列化的字段赋值。

代码

实际执行的文件操作

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

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

public class FileAnalysis : IFileOperation<string[]>
{
private string[] m_folders;
private Predicate<string> m_fileFilter;
private Regex m_regexCheck;

private CancellationTokenSource m_tokenSource;
private CancellationToken m_cachedToken;

public Task<string[]> OperationTask { get; set; }
public float PercentCompletion { get; set; }
public string CurrentOperationMessage { get; set; }
public int FileCount { get; set; }
public int Operated { get; set; }
public bool Running => OperationTask.Status switch
{
TaskStatus.RanToCompletion => false,
TaskStatus.Faulted => false,
TaskStatus.Canceled => false,
_ => true
};

public CancellationToken Token => m_cachedToken;

public static IFileOperation<string[]> AnalyzeFolders(string[] folders, Predicate<string> fileFilter, Regex regexCheck)
{
FileAnalysis operation = new FileAnalysis(folders, fileFilter, regexCheck);
operation.DoOperation();
return operation;
}

public FileAnalysis(string[] folders, Predicate<string> fileFilter, Regex regexCheck)
{
m_folders = folders;
m_fileFilter = fileFilter;
m_regexCheck = regexCheck;
m_tokenSource = new CancellationTokenSource();
}

public void Cancel()
{
if (null != m_tokenSource)
{
m_tokenSource.Cancel();
m_tokenSource.Dispose();
m_tokenSource = null;
}
}

public void DoOperation()
{
if (null == OperationTask)
{
try
{
OperationTask = Task.Factory.StartNew<string[]>(CheckFolders, cancellationToken: m_cachedToken = m_tokenSource.Token);
}
catch (Exception _) { }
}
}

private string[] CheckFolders()
{
string[] files = m_folders.SelectMany(folder => Directory.GetFiles(folder, "*", SearchOption.AllDirectories)).ToArray();
List<string> result = new List<string>(200);
int count = files.Length;
FileCount = count;
Operated = 0;
PercentCompletion = 0f;
for (int i = 0; i < count; i++)
{
Token.ThrowIfCancellationRequested();
string filePath = files[i];
if (m_fileFilter(filePath))
{
CurrentOperationMessage = filePath;
if (CheckFile(filePath, m_regexCheck))
{
result.Add(filePath.Replace('\\', '/'));
}
Operated++;
PercentCompletion = (i / (float)count) * 100f;
}
}
return result.ToArray();
}
private bool CheckFile(string filepath, Regex check)
{
string assetText = File.ReadAllText(filepath);
MatchCollection matches = check.Matches(assetText);
bool result = matches.Count > 0;
return result;
}

}

public class FileTextReplace : IFileOperation<string[]>
{
private string[] m_fullPaths;
private string m_prevText;
private string m_nextText;

private CancellationTokenSource m_tokenSource;
private CancellationToken m_cachedToken;

public Task<string[]> OperationTask { get; private set; }
public float PercentCompletion { get; private set; }
public string CurrentOperationMessage { get; private set; }
public int FileCount { get; private set; }
public int Operated { get; private set; }
public bool Running => OperationTask.Status switch
{
TaskStatus.RanToCompletion => false,
TaskStatus.Faulted => false,
TaskStatus.Canceled => false,
_ => true
};

public CancellationToken Token => m_cachedToken;

public static IFileOperation<string[]> ReplaceText(string[] fullpaths, string prevText, string nextText)
{
FileTextReplace operation = new FileTextReplace(fullpaths, prevText, nextText);
operation.DoOperation();
return operation;
}

public FileTextReplace(string[] fullpaths, string prevText, string nextText)
{
m_fullPaths = fullpaths;
m_prevText = prevText;
m_nextText = nextText;
m_tokenSource = new CancellationTokenSource();
}

public void DoOperation()
{
if (null == OperationTask)
{
try
{
OperationTask = Task.Factory.StartNew<string[]>(DoReplaceToFiles, cancellationToken: m_cachedToken = m_tokenSource.Token);
}
catch (Exception _) { }
}
}

public void Cancel()
{
if (null != m_tokenSource)
{
m_tokenSource.Cancel();
m_tokenSource.Dispose();
m_tokenSource = null;
}
}

private string[] DoReplaceToFiles()
{
List<string> temp = new List<string>();
Operated = 0;
FileCount = m_fullPaths.Length;
for (int i = 0, length = m_fullPaths.Length; i < length; i++)
{
Token.ThrowIfCancellationRequested();
string assetFullPath = m_fullPaths[i];
string assetText = File.ReadAllText(assetFullPath);
string nextAssetText = assetText.Replace(m_prevText, m_nextText);
File.WriteAllText(assetFullPath, nextAssetText);
temp.Add(assetFullPath);
Operated++;
CurrentOperationMessage = assetFullPath;
PercentCompletion = (i / (float)length) * 100f;
}
if (0 < temp.Count)
{
return temp.ToArray();
}
return null;
}

}
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
390
391
392
393
394
395
396
397
398
399
400

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;
}
}
}

[Serializable]
private struct AssetResult
{
public string fullPath;
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 IFileOperation<string[]> m_operationTask = null;
private bool m_waitForResult = false;
private AssetResult[] m_assetResults = null;
private Regex m_pathFilterRegex;

private Vector2 m_scrollPos;
private Stopwatch m_processTime;

private string m_searchReplaceText = string.Empty;

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

[MenuItem("Tools/Temp Asset Usage Search", priority = 4)]
private static void OpenWindowLah()
{
if (EditorWindow.HasOpenInstances<AssetUsageSearchWindow>())
{
UnityDebug.LogError($"Editor window {nameof(AssetUsageSearchWindow)} can only have 1 instance.");
return;
}
AssetUsageSearchWindow window = CreateWindow<AssetUsageSearchWindow>();
window.Show();

// init
window.titleContent = new GUIContent("Asset Usage Search");
window.RefreshPathFilter();
}

private void OnGUI()
{
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
bool isSearching = null != m_operationTask && m_operationTask.OperationTask.Status == TaskStatus.Running;
bool isFaulted = null != m_operationTask && m_operationTask.OperationTask.Status == TaskStatus.Faulted;

using (new EditorGUI.DisabledGroupScope(IsBusy))
{
// draw search info
m_searchTextOnly = EditorGUILayout.Toggle("Search Text Only", m_searchTextOnly);
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);
m_searchReplaceText = EditorGUILayout.TextField("Replace Text", m_searchReplaceText);
}
else
{
bool prev = GUI.enabled;
GUI.enabled = false;
request.targetString = EditorGUILayout.TextField(request.targetString);
GUI.enabled = prev;
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("Asset Filter", m_filter);

// Draw folder
EditorGUILayout.LabelField("Target folders:");
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
if (GUILayout.Button("Add Folder"))
{
m_searchFolders.Add(Application.dataPath);
}
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;
}
}
}

// search button
if (GUILayout.Button($"Search References for \"{m_search.targetString}\"") && !string.IsNullOrEmpty(m_search.targetString))
{
DoSearch();
}

// replace button
if (!IsBusy && !isSearching && !isFaulted && m_searchTextOnly && (null != m_assetResults && 0 < m_assetResults.Length))
{
if (GUILayout.Button($"Replace Text"))
{
DoTextReplace(); // TODO @Hiko use task to prevent editor window STUCK :(
}
}
}

if (isSearching) DrawOperatingGUI();
else if (isFaulted) EditorGUILayout.HelpBox($"Error while running search:\n{m_operationTask.OperationTask.Exception}", MessageType.Error);
else if (m_assetResults != null) DrawOperationResultGUI();
}
}

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

private void DoTextReplace()
{
List<string> pathList = new List<string>(m_assetResults.Length);
for (int i = 0, length = m_assetResults.Length; i < length; i++)
{
AssetResult searchResult = m_assetResults[i];
//if (searchResult.subAssetIfNeed)
//{
// continue;
//}
pathList.Add(searchResult.fullPath);
}
if (0 < pathList.Count)
{
if (EditorUtility.DisplayDialog("Are you sure?", "The operation can not be canceled", "Yes just do it", "Dun do it"))
{
m_assetResults = Array.Empty<AssetResult>();
m_processTime = Stopwatch.StartNew();
m_operationTask = FileTextReplace.ReplaceText(pathList.ToArray(), m_search.targetString, m_searchReplaceText);
m_waitForResult = true;
}
}
}

private void DoSearch()
{
m_assetResults = Array.Empty<AssetResult>();
m_processTime = Stopwatch.StartNew();
RefreshPathFilter();
m_operationTask = FileAnalysis.AnalyzeFolders(m_searchFolders.Count > 0 ? m_searchFolders.ToArray() : new string[] { Application.dataPath }, FilterPath, new Regex(m_search.targetString));
m_waitForResult = true;
}

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

private void DrawOperatingGUI()
{
EditorGUILayout.LabelField($"Operating: {m_operationTask.PercentCompletion:F2}%");
EditorGUILayout.LabelField(m_operationTask.CurrentOperationMessage);
if (GUILayout.Button("Cancel"))
{
m_operationTask.Cancel();
//m_operationTask = null;
m_processTime.Stop();
}
}

private void DrawOperationResultGUI()
{
EditorGUILayout.LabelField($"Result {m_assetResults.Length} assets:");
if (null != m_processTime)
{
if (m_processTime.IsRunning)
{
m_processTime.Stop();
}
if (m_operationTask is FileAnalysis)
{
EditorGUILayout.LabelField($"Operation time {m_processTime.ElapsedMilliseconds}ms, {m_operationTask.Operated}/{m_operationTask.FileCount} files scanned");
}
else if (m_operationTask is FileTextReplace)
{
EditorGUILayout.LabelField($"Operation time {m_processTime.ElapsedMilliseconds}ms, {m_operationTask.Operated}/{m_operationTask.FileCount} files got text replced");
}
}
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Copy list to clipboard", EditorStyles.miniButton))
{
GUIUtility.systemCopyBuffer = string.Join("\n", m_assetResults.Select(rst => rst.fullPath));
}
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_assetResults.Length; i++)
{
using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox))
{
AssetResult result = m_assetResults[i];
Rect foldoutRect = GUILayoutUtility.GetRect(20, EditorGUIUtility.singleLineHeight, GUILayout.Width(20));
EditorGUILayout.ObjectField(result.asset, typeof(UnityObject), false);
string assetFullPath = result.fullPath;
if (GUILayout.Button(new GUIContent(assetFullPath, result.fullPath)))
{
UnityDebug.Log($"copy full path {assetFullPath} to clipboard");
GUIUtility.systemCopyBuffer = assetFullPath;
EditorGUIUtility.PingObject(result.asset);
}
m_assetResults[i] = result;
EditorGUILayout.EndFoldoutHeaderGroup();
}
}
}
}
}

private void Update()
{
if (null != m_operationTask)
{
if (m_operationTask.OperationTask.Status == TaskStatus.Running)
{
Repaint();
}
else if (m_operationTask.OperationTask.Status == TaskStatus.RanToCompletion && m_waitForResult)
{

if (m_operationTask is FileAnalysis) { }
else if (m_operationTask is FileTextReplace)
{
string[] results = m_operationTask.OperationTask.Result;
string tempLog = string.Empty;
for (int i = 0, length = results.Length; i < length; i++)
{
string assetFullPath = results[i];
AssetDatabase.ImportAsset(assetFullPath);
string assetPath = assetFullPath.Substring(Application.dataPath.Length - 6);
tempLog += $"{assetPath}\n";
}

UnityDebug.Log($"Do Text reaplce for asset:\n {tempLog}");
EditorUtility.DisplayDialog("Done", $"Did text replace for {results.Length} files", "OK");
AssetDatabase.Refresh();
}

// Result filling is done here because it needs to run on main thread
m_waitForResult = false;
string[] result = m_operationTask.OperationTask.Result;
int count = result.Length;
if (0 == count)
{
m_assetResults = Array.Empty<AssetResult>();
}
else
{
if (null == m_assetResults)
{
m_assetResults = new AssetResult[count];
}
else if (m_assetResults.Length != count)
{
Array.Resize(ref m_assetResults, count);
}
}
for (int i = 0; i < count; i++)
{
string assetPath = $"Assets{result[i].Substring(Application.dataPath.Length)}";
UnityObject asset = AssetDatabase.LoadAssetAtPath<UnityObject>(assetPath);
m_assetResults[i] = new AssetResult
{
fullPath = 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毫无关系,用Task跑还可以可以避免长时间的卡死,而且我们也能加入取消的功能。如果在乎性能的话可以还可以在读文件检查这边做优化。不过感觉这样已经比之前快了许多了。