Skip to content

Commit e0ed398

Browse files
author
BlackSpiral15
committed
Small fixes in DeadScripts' editor
1 parent 9c3726c commit e0ed398

File tree

4 files changed

+109
-47
lines changed

4 files changed

+109
-47
lines changed

Assets/DeadScriptsSearcher/Examples/DemoBroken.unity

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1985,7 +1985,7 @@ Transform:
19851985
m_LocalScale: {x: 1, y: 1, z: 1}
19861986
m_Children: []
19871987
m_Father: {fileID: 0}
1988-
m_RootOrder: 1
1988+
m_RootOrder: 5
19891989
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
19901990
--- !u!1 &437272557
19911991
GameObject:

Assets/DeadScriptsSearcher/Scripts/CoreFunctions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
using UnityEngine;
33
using UnityEngine.SceneManagement;
44

5-
namespace Spiral.Core
5+
namespace Spiral.EditorTools.DeadScriptsSearcher
66
{
77
/// <summary>
88
/// Некоторые функции из моей основной библиотеки, которую я не буду выкладывать целиком

Assets/DeadScriptsSearcher/Scripts/DeadScripts.cs

Lines changed: 64 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using System.Collections.Generic;
22
using UnityEngine;
3-
using Spiral.Core;
3+
using UnityEngine.SceneManagement;
44

55
#if UNITY_EDITOR
66
using UnityEditor;
@@ -13,6 +13,18 @@ public class DeadScripts : MonoBehaviour
1313
public List<ObjectID> deadIDs { get; private set; } = new List<ObjectID>();
1414
private SceneFile sceneFile = null;
1515

16+
public bool sceneFileLoaded
17+
{
18+
get
19+
{
20+
if (sceneFile == null) return false;
21+
if (sceneFile.count == 0) return false;
22+
return true;
23+
}
24+
}
25+
26+
public bool isDirty { get { return SceneManager.GetActiveScene().isDirty; } }
27+
1628
public void SelectDeads()
1729
{
1830
List<GameObject> selectObjects = new List<GameObject>();
@@ -54,10 +66,10 @@ public void UpdateDeadList()
5466
}
5567
}
5668

57-
public void SearchForDeads(bool updateDeads = true)
69+
public void SearchForDeads()
5870
{
5971
// обновляемся
60-
if (updateDeads) UpdateDeadList();
72+
UpdateDeadList();
6173

6274
// прогружаем файл сцены
6375
sceneFile = new SceneFile();
@@ -124,59 +136,78 @@ public void SearchForDeads(bool updateDeads = true)
124136
[CustomEditor(typeof(DeadScripts))]
125137
public class DeadScriptsEditor : Editor
126138
{
127-
private DeadScripts deadmono = null;
128-
139+
private DeadScripts deadmono = null;
140+
129141
private void OnEnable()
130142
{
131143
deadmono = serializedObject.targetObject as DeadScripts;
132144
}
133145

134-
public override void OnInspectorGUI()
146+
private void DrawDebugMode()
135147
{
136148
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
137-
EditorGUILayout.LabelField("ПОИСК МЁРТВЫХ СКРИПТОВ:", EditorStyles.boldLabel);
138-
149+
EditorGUILayout.LabelField("Режим отладки:", EditorStyles.miniBoldLabel);
150+
deadmono.debug = EditorGUILayout.Toggle("Включить режим отладки", deadmono.debug);
151+
EditorGUILayout.HelpBox("Режим отладки будет выводить в консоль все действия, что может " +
152+
"существенно замедлить осмотр сцен с большим количеством объектов;",
153+
MessageType.Warning);
154+
EditorGUILayout.EndVertical();
155+
}
139156

157+
private void DrawSimpleMode()
158+
{
140159
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
141-
EditorGUILayout.LabelField("Только объекты:", EditorStyles.miniBoldLabel);
160+
EditorGUILayout.LabelField("Только объекты:", EditorStyles.boldLabel);
142161
if (GUILayout.Button("Найти и выделить"))
143162
{
144163
deadmono.UpdateDeadList();
145164
deadmono.SelectDeads();
146165
}
147-
if (GUILayout.Button("Выделить"))
148-
{
149-
deadmono.SelectDeads();
150-
}
151-
EditorGUILayout.HelpBox("При нажатии на [Выделить] выполняется попытка выделить все объекты, " +
152-
"которые ранее были опознаны как содержащие мёртвые скрипты. " +
153-
"Проверьте, что поиск уже был выполнен, " +
154-
"в противном случае используйте опцию [Найти и выделить];",
155-
MessageType.Warning);
166+
EditorGUILayout.HelpBox("При нажатии выполняется попытка найти и выделить все " +
167+
"объекты с битыми скриптами, находящиеся на сцене",
168+
MessageType.None);
156169
EditorGUILayout.EndVertical();
170+
}
157171

172+
private void DrawBoxSceneState()
173+
{
158174
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
159-
EditorGUILayout.LabelField("Проверка файла сцены:", EditorStyles.miniBoldLabel);
175+
EditorGUILayout.LabelField("Проверка файла сцены:", EditorStyles.boldLabel);
176+
177+
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
178+
179+
EditorGUILayout.BeginHorizontal(GUI.skin.box);
180+
GUIStyle styleSceneIsDirty = new GUIStyle(EditorStyles.boldLabel);
181+
string sceneIsDirty = deadmono.isDirty ? "СЦЕНА БЫЛА ИЗМЕНЕНА!" : "СЦЕНА СОХРАНЕНА";
182+
styleSceneIsDirty.normal.textColor = deadmono.isDirty ? new Color(0.8f, 0.0f, 0.0f) : Color.gray;
183+
EditorGUILayout.LabelField(sceneIsDirty, styleSceneIsDirty);
184+
EditorGUILayout.EndHorizontal();
160185
EditorGUILayout.HelpBox("Убедитесь, что сцена была сохранена, поскольку поиск будет идти по файлу сцены.\n" +
161-
"Для сцен с большим количеством объектов поиск может идти медленно!",
162-
MessageType.Warning);
163-
if (GUILayout.Button("Показать мёртвые GUID (с обновлением)"))
164-
{
165-
deadmono.SearchForDeads(true);
166-
}
167-
if (GUILayout.Button("Показать мёртвые GUID (без обновления)"))
186+
"Для сцен с большим количеством объектов поиск может идти медленно!",
187+
MessageType.Warning);
188+
EditorGUILayout.EndVertical();
189+
190+
if (GUILayout.Button("Показать мёртвые GUID"))
168191
{
169-
deadmono.SearchForDeads(false);
192+
deadmono.SearchForDeads();
170193
}
194+
EditorGUILayout.HelpBox("Поиск идёт по файлу сцены, сопоставляя объекты с битыми скриптами " +
195+
"с их записями в файле. Все результаты будут выведены в консоль. " +
196+
"Обратите внимание, что из поиска исключаются скрипты, " +
197+
"не являющиеся MonoBehaviour, а также дочерние объекты в составе префабов!",
198+
MessageType.None);
199+
171200
EditorGUILayout.EndVertical();
201+
}
172202

203+
public override void OnInspectorGUI()
204+
{
173205
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
174-
EditorGUILayout.LabelField("Режим отладки:", EditorStyles.miniBoldLabel);
175-
deadmono.debug = EditorGUILayout.Toggle("Включить режим отладки", deadmono.debug);
176-
EditorGUILayout.HelpBox("Режим отладки будет выводить в консоль все действия, что может " +
177-
"существенно замедлить осмотр сцен с большим количеством объектов;",
178-
MessageType.Warning);
179-
EditorGUILayout.EndVertical();
206+
EditorGUILayout.LabelField("ПОИСК МЁРТВЫХ СКРИПТОВ:", EditorStyles.boldLabel);
207+
208+
DrawDebugMode();
209+
DrawSimpleMode();
210+
DrawBoxSceneState();
180211

181212
EditorGUILayout.EndVertical();
182213
}

Assets/DeadScriptsSearcher/Scripts/SceneFile.cs

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,48 @@ public class SceneFile
3737

3838
// FUNCTIONALITY ==========================================================================
3939
//=========================================================================================
40-
private readonly List<string> scene = new List<string>();
40+
private Scene inspectedScene;
41+
private readonly List<string> file = new List<string>();
42+
public int count { get { return file.Count; } }
43+
public string this[int idx]
44+
{
45+
get
46+
{
47+
if (idx >= count) return string.Empty;
48+
if (idx < 0) return string.Empty;
49+
return file[idx];
50+
}
51+
private set
52+
{
53+
if (idx >= count) Debug.LogWarning("IDX is out of bound");
54+
if (idx < 0) Debug.LogWarning("IDX is out of bound");
55+
file[idx] = value;
56+
}
57+
}
58+
59+
public void SaveScene(string newName = "")
60+
{
61+
string scenePath = inspectedScene.path;
62+
FileInfo fileInfo = new FileInfo(scenePath);
63+
64+
if (string.IsNullOrEmpty(newName)) newName = fileInfo.Name;
65+
if (!newName.Contains(".unity")) newName += ".unity";
66+
newName = fileInfo.DirectoryName + @"\" + newName;
67+
scenePath = newName;
68+
69+
File.WriteAllLines(scenePath, file.ToArray());
70+
}
4171

4272
public SceneFile(Scene scene)
4373
{
44-
this.scene = GetSceneText(scene);
74+
inspectedScene = scene;
75+
file = GetSceneText(scene);
4576
}
4677

4778
public SceneFile()
4879
{
49-
Scene scene = SceneManager.GetActiveScene();
50-
this.scene = GetSceneText(scene);
80+
inspectedScene = SceneManager.GetActiveScene();
81+
file = GetSceneText(inspectedScene);
5182
}
5283

5384
/// <summary>
@@ -59,7 +90,7 @@ public SceneFile()
5990
/// -2, если объект находится в составе префаба</returns>
6091
public int IndexOfObject(ObjectID oid)
6192
{
62-
int strIDX = scene.FindIndex(x => x.Contains($"&{oid.id}"));
93+
int strIDX = file.FindIndex(x => x.Contains($"&{oid.id}"));
6394
if (strIDX < 0)
6495
{
6596
if (oid.globalID.targetObjectId == 0) return -1;
@@ -77,7 +108,7 @@ public int IndexOfObject(ObjectID oid)
77108
/// <returns></returns>
78109
public int IndexOfComponent(ulong componentGID)
79110
{
80-
return scene.FindIndex(x => x.Contains($"&{componentGID}"));
111+
return file.FindIndex(x => x.Contains($"&{componentGID}"));
81112
}
82113

83114
/// <summary>
@@ -111,19 +142,19 @@ public string GetGUID(ulong componentGID, bool debug)
111142

112143
string line;
113144
int cursor = strIDX;
114-
line = scene[cursor];
145+
line = file[cursor];
115146
if (!IsMono(line, false, 0))
116147
{
117148
if (debug) Debug.Log($"Script is not mono: {line}");
118149
return string.Empty;
119150
}
120151

121-
int eof = scene.Count - 1;
152+
int eof = file.Count - 1;
122153
cursor += 2;
123154
bool mscriptFound = false;
124155
while (cursor < eof)
125156
{
126-
cursor++; line = scene[cursor];
157+
cursor++; line = file[cursor];
127158
if (line.Contains(unitSeparator)) { break; }
128159
if (line.Contains(unitMonoScriptField)) { mscriptFound = true; break; }
129160
}
@@ -158,14 +189,14 @@ private List<ulong> GetComponentsGIDs(int fromIDX, bool debug)
158189
string currentLine; // читалка строки
159190
int cursor = fromIDX; // текущая позиция в файле
160191

161-
int eofIDX = scene.Count;
192+
int eofIDX = file.Count;
162193

163194
List<ulong> gids = new List<ulong>();
164195

165196
// идём от GameObject до конца файла, не читая последнюю строчку
166197
while (cursor < eofIDX)
167198
{
168-
cursor++; currentLine = scene[cursor];
199+
cursor++; currentLine = file[cursor];
169200

170201
// дошли до следующего разделителя - дропаемся
171202
if (currentLine.Contains(unitSeparator)) { break; }
@@ -175,7 +206,7 @@ private List<ulong> GetComponentsGIDs(int fromIDX, bool debug)
175206
{
176207
while (cursor < eofIDX)
177208
{
178-
cursor++; currentLine = scene[cursor];
209+
cursor++; currentLine = file[cursor];
179210
if (!currentLine.Contains("component")) break; // вышли из списка компонент
180211
ulong gid = GetFileIDFromLine(currentLine);
181212
gids.Add(gid);

0 commit comments

Comments
 (0)