Question About Namespaces

Hello, I am a Unity Newbie but I’ve created a few full projects (Mostly based on demos). My question is about the namespaces identified at the top of a newly created C# script. I have never experimented with using any namespaces outside of the default ones it provides, but I’ve ran into problems when building my games that have to do with unidentified namespaces in my scripts. For example, I just built a project and got a failed result because “using UnityEditor.SearchService;” was at the top of the one script in the program. I deleted that line and the project build normally. Another example is “using UnityEditor.Build.Content;”. My question is, why was that there in the first place? My other scripts usually build fine, but this has happened multiple times with different unidentified namespaces. I don’t understand why namespaces that prevent my project from building just occasionally pop up in my scripts. I’m using Visual Studio by the way.

That’s an annoying thing that can happen when you use an IDE with auto completion and you autocomplete identifiers which exist in multiple places. For instance, in Unity there is both “UnityEngine.SceneManagement.Scene” and “UnityEditor.SearchService.Scene” which do totally different things. If you accidentally cause the wrong namespace to be added from auto complete or whatever, you need to undo enough times to cancel the namespace addition as well. Generally try to be careful whenever you autocomplete something or auto-add missing using statements. Rider tends to give you multiple options somewhere, not sure about the Visual Studio product line.

Any Editor related namespaces will prevent you from building your game, that’s includes any namespace start with “UnityEditor.”.

This is true also from editor scripts, thats why you need to put them inside “Editor” folder.

A simple solution is, if you are using visual studio, you can auto-remove unused namespaces when you save your script (Which can be done in the setting/preference).

I have a hotkey in Rider that performs a „code cleanup“. You can set it up to do so on save even. One of the things this does, besides reformatting all code to look the same, is to remove unused using statements.

Not sure if a useful feature like this exists in inferior IDEs though. :smile:
When I was still with VS I had to run an external tool command called „uncrustify“ to cleanup the code. And that tool supported every language and so was a pain to set up and often failed to consider or support C# special cases.

Well, the latest preview of VS seems to have this feature as well ^^

3 Likes

And you can already just hit the code cleanup button at the bottom. It looks like a little dustpan broom. You can configure what exactly it does as well. I like that it removes unused usings, but you have to remember that if I comment something out and hit code cleanup it might remove a using statement that only the commented out code was using.