Skip to content

Instantly share code, notes, and snippets.

@thebne
Created November 11, 2021 13:31
Show Gist options
  • Save thebne/42551f7e15e1701cd52aca16d6512fce to your computer and use it in GitHub Desktop.
Save thebne/42551f7e15e1701cd52aca16d6512fce to your computer and use it in GitHub Desktop.
Rename Unity's managed reference (ones created by [SerializeReference] attribute)
import os
import sys
DEFAULT_ASSEMBLY = "Assembly-CSharp"
DEFAULT_NS = ""
def main():
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} <old assembly:?><old ns:?><old name> <new assembly:?><new ns:?><new name>")
print()
print(f"Example: {sys.argv[0]} GameTeller.Graph:DeepFrameBeat Underdogs.GameTeller:GameTeller.Graph:DFBeat")
print(f"By default assembly = {DEFAULT_ASSEMBLY}, ns = {DEFAULT_NS}")
return
parts = sys.argv[1].split(":")[::-1]
if len(parts) > 3:
raise ValueError(f"argument '{sys.argv[1]}': too many colons")
old_assembly = parts[2] if len(parts) >= 3 else DEFAULT_ASSEMBLY
old_ns = parts[1] if len(parts) >= 2 else DEFAULT_NS
old_name = parts[0]
parts = sys.argv[2].split(":")[::-1]
if len(parts) > 3:
raise ValueError(f"argument '{sys.argv[2]}': too many colons")
new_assembly = parts[2] if len(parts) >= 3 else DEFAULT_ASSEMBLY
new_ns = parts[1] if len(parts) >= 2 else DEFAULT_NS
new_name = parts[0]
replace_str_old = f"type: {{class: {old_name}, ns: {old_ns}, asm: {old_assembly}}}"
replace_str_new = f"type: {{class: {new_name}, ns: {new_ns}, asm: {new_assembly}}}"
try:
print("Replacing")
print(f"> {replace_str_old}")
print("with")
print(f"> {replace_str_new}")
input("Press any key to continue or CTRL+C to abort")
except KeyboardInterrupt:
print("abort")
return
print()
count = 0
file_count = 0
for root, dirs, files in os.walk("..\Assets"):
for fp in files:
path = os.path.join(root, fp)
try:
if fp.endswith(".asset"):
with open(path, "r") as f:
contents = f.read()
this_file_count = contents.count(replace_str_old)
if this_file_count == 0:
continue
print(f"Replacing in {path} ({this_file_count} occurences)")
with open(path, "w") as f:
f.write(contents.replace(replace_str_old, replace_str_new))
count += this_file_count
file_count += 1
except Exception as e:
print(f"Could not replace in file {path}:")
print(e)
print()
print(f"Replaced {count} occurences in {file_count} files")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment