Skip to content

Instantly share code, notes, and snippets.

@IJEMIN
Forked from sokcuri/remove-missing-script.py
Created March 21, 2019 11:05
Show Gist options
  • Save IJEMIN/37b1c771c08e9d1938a7bbf04c68f4af to your computer and use it in GitHub Desktop.
Save IJEMIN/37b1c771c08e9d1938a7bbf04c68f4af to your computer and use it in GitHub Desktop.
유니티 프리팹에서 Missing Script를 일괄 삭제하는 파이썬 스크립트입니다
# remove-missing-script.py
# A Python script that removes the disconnected script file "Missing Script" in Unity Prefab files
# - Author: github.com/sokcuri
#
# usage:
# > python Tools/remove-missing-script.py [Target Folder]
#
import re, sys
from pathlib import Path
re_ptn_guid = re.compile('^guid:\s(.+)$', re.MULTILINE)
re_ptn_script = re.compile('m_Script:\s{fileID:\s[^,].+,\sguid:\s([^,].+),\stype:\s.+}', re.MULTILINE)
# --- !u!1001 &100100000
re_ptn_sect = re.compile(r'^-', re.MULTILINE)
def collect_guid(paths):
print('Collecting meta files...')
guids = {}
file_list = list(Path(paths).rglob('*.meta'))
for i, file_name in enumerate(file_list):
for j, line in enumerate(open(file_name)):
for m in re.finditer(re_ptn_guid, line):
# print(p.with_suffix(''))
# \a\b\c
# print(p.stem)
# c
guids[m.group(1)] = Path(file_name).with_suffix('')
# print(f'{i} {file_name} {m.group(1)}')
return guids
def remove_mb_section(lines, curr_line):
lower = 0
upper = len(lines)
for i in range(curr_line, upper, 1):
line = lines[i][1]
if re.search(re_ptn_sect, line[0]):
upper = i
break
else:
upper = -1
for i in range(curr_line, lower, -1):
line = lines[i][1]
if re.search(re_ptn_sect, line[0]):
lower = i
break
else:
lower = -1
print(f' - Remove MonoBehaviour: {lower}-{upper}')
if lower == -1 or upper == -1:
return False
del lines[lower:upper]
return lines
def load_file(name, guids):
print(f'Loading files: {name}')
lines = []
items = []
with open(name, 'r') as f:
for line in enumerate(f):
lines.append(line)
for i in range(len(lines), 0, -1):
line = str(lines[i - 1])
for m in re.finditer(re_ptn_script, line):
if not m.group(1) in guids:
items.append(i)
print(f'Found Missing Script: {i} {m.group(1)}')
for i in items:
print(f'Removing Missing Script: {name}:{i}')
res = remove_mb_section(lines, i)
if not res == False:
lines = res
with open(name, 'w') as f:
for i, line in lines:
f.write(line)
def process(paths, guids):
files = list(Path(paths).rglob('*.prefab'))
for i, name in enumerate(files):
load_file(name, guids)
def main():
target = sys.argv[1]
if len(sys.argv) == 1:
print('Usage: ')
print(' python remove-missing-script.py [target folder]')
return
if not Path('Assets').exists():
print('Should be run Unity project root folder.')
return
if not Path(target).exists():
print('Target folder should be exist.')
return
guids = collect_guid('Assets')
process(target, guids)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment