Question3r
Question3r

Reputation: 3752

How to setup namespaces based on folder structure for Unity

I downloaded Unity 20.2 and want to use namespaces for my code. I modified my project settings to this

enter image description here

In the editor I now have this folder structure for my code

enter image description here

The problem is that the created script Test has the namespace Sources although I would expect it to be Sources.Scripts. I also tried Assets.Sources but it still is not able to create Assets.Sources.Scripts from it.

How can I achieve this?

Upvotes: 2

Views: 5307

Answers (4)

KaiStarkk
KaiStarkk

Reputation: 1

I was able to fix the same issue by disabling "Generate Player .csproj files" in editor setting, then deleting the .csproj files and regenerating.

Upvotes: 0

Viktor Kadza Jr.
Viktor Kadza Jr.

Reputation: 318

If you are using Rider , then try this. Resharper has the same option. I don't use neither of them , so , have to use Select(Assets) + Del everytime making a new class.

Upvotes: 0

Viktor Kadza Jr.
Viktor Kadza Jr.

Reputation: 318

If you create a class in Visual Studio, then it automatically gets the namespace from the folder structure. Like assets.scripts.something. Just create classes in the correct place and you will get all needed namespaces.

Upvotes: 2

Carlos Sala Samper
Carlos Sala Samper

Reputation: 31

I'm going to describe a situation with some packages in a project to explain this:

Imagine a project in Unity3D with a directory structure like this:

  • Assets
    • Resources
    • Scenes
    • Source/Scripts
      • UI
        • Buttons
        • Modals

Namespaces convention in this case is driven by the programming language used (C#) in the project (First letter in uppercase, matching the name of the folders).

I suggest you to ignore the directory path until the "Source" or "Scripts" folder when you are choosing the namespaces of your packages. Then in this project we would have this 2 packages:

  • ProjectName.UI.Buttons
  • ProjectName.UI.Modals

Conclusion: Write your own namespaces, because Unity namespaces generation is based on folders structure from root and I think that is not the best if you want to share your code by modules, for example.

Good luck, bro 💚

Upvotes: 0

Related Questions