Skip to content

Instantly share code, notes, and snippets.

@thebne
Created July 7, 2021 17:33
Show Gist options
  • Save thebne/ffa178b6aab6cff9bbd4d3069a5133ab to your computer and use it in GitHub Desktop.
Save thebne/ffa178b6aab6cff9bbd4d3069a5133ab to your computer and use it in GitHub Desktop.
Find unused Script references in Unity - using meta GUIDs + naïve Regular Expressions
import os, sys
import unityparser
import re
def get_files(folder_path):
return [x for f in os.walk(folder_path) for x in map(lambda x: f"{f[0]}{os.path.sep}{x}", f[2])]
scripts = {d.data[0]['guid']: d for d in [unityparser.UnityDocument.load_yaml(path) for path in get_files(os.path.join('Assets', 'Scripts')) if path.endswith(".meta")]}
assets_paths = [path for path in get_files('Assets') if path.endswith('.unity') or path.endswith('.prefab') or path.endswith('.asset')]
i = 0
total = len(assets_paths)
found = set()
for path in assets_paths:
i += 1
if i % 10 == 0:
print(f"{i} / {total} ({float(i) / total * 100}%)")
try:
doc = unityparser.UnityDocument.load_yaml(path)
except UnicodeDecodeError:
# some files aren't yamls...
continue
monos = doc.filter(class_names=('MonoBehaviour',))
for mono in monos:
guid = mono.m_Script['guid']
if guid in scripts:
print(f"Found dependency: {doc.file_path}->{scripts[guid].file_path}")
found.add(guid)
not_found = set(scripts.keys()).difference(found)
# find (naive) references in all script files
names = list()
for guid in not_found:
path = scripts[guid].file_path
if not path.endswith(".cs.meta"):
continue
script_name = os.path.basename(path[:-len(".cs.meta")])
names.append((guid, script_name))
names_re = [(guid, re.compile(f"(^|\W){name}($|\W)")) for guid, name in names]
# scan through scripts only
for script_guid, meta in scripts.items():
if not meta.file_path.endswith(".cs.meta"):
continue
script_path = meta.file_path[:-len(".meta")]
contents = open(script_path, "r").read()
for guid, compiled in names_re:
if script_guid == guid:
continue
if len(compiled.findall(contents)):
print(f"Found naive reference: {script_path}->{compiled}")
not_found.discard(guid)
sorted_not_found = sorted(not_found, key=lambda x: scripts[x].file_path)
for guid in sorted_not_found:
path = scripts[guid].file_path
if not path.endswith(".cs.meta"):
continue
script_path = path[:-len(".meta")]
print(guid, script_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment