Last Updated: November 19, 2020
·
13.92K
· ProGM

Remove unused files from Unity3d project

Lately, I took back an old game project I did one year ago with my team for a contest.

Since I didn't touch it till August 2015, and it was really a mess:
Upgrading to Unity 5.3 was really a pain in the ass. However, I (kinda) did it.

After working a bit on it, I noticed it was full of garbage: Old graphics, unused script, unreferenced prefabs... So I wrote a script to identify all unused files on a project!

(To be honest, I already the same script for unity 4.6, but I had to update it a bit.)
The idea is pretty simple: It scans every file in the Assets folder and creates a report file (unused_files.log) that contains every file without a reference. Then, you can manually delete them.

Here's the source!
https://gist.github.com/ProGM/18111dfef2477407c1c1

How it works

First of all, I assume that you are serializing your assets as text. If you don't, do it now.

This is very useful if you want to put the project on a version control system.

Detecting assets (images, sounds, etc...)

Unity generates an unique guid for every resource in the project, and uses this to reference them inside other resources. For example, if you use an image cat.png in your animals.unity scene, it saves a guid like this in your cat.png.meta:

fileFormatVersion: xxx
guid: aeb3fc58ba68b4f578af5d1e24990302
timeCreated: xxxxx
licenseType: YourLicense
...

Then it references it in your scene file:

m_YourData:
- {fileID: 10754, guid: aeb3fc58ba68b4f578af5d1e24990302, type: 0}

So, checking if an asset is referenced, is pretty simple!

Detecting unused scenes

For "unused scenes" I mean: Scenes that are not built in the final project. How to detect them? Simple! Check if it appears in your ProjectSettings/EditorBuildSettings.asset.

Detect unused scripts

The standard check works also with MonoBehavior scripts. However it doesn't cover every case. For example, it doesn't reference every script that is not a MonoBehavior.
To check them, I simply scan any other *.cs file, and I check if that class name is referenced in it.
For this, it's a best-effort method, since it doesn't account .js and .boo files. However, implementing them is pretty straight-forward. Obviously this doesn't deal with namespaces, but that's another pair of shoes.

However, to detect unused classes (and more), a better way is to use a static code analyzer, like Reshaper.

Related protips:

Improved PlayerPrefs for Unity