Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by DontShooot · Mar 17, 2015 at 03:15 PM · c#namespaceorganization

Namespaces usage recommendation

I'm used to create a lot of small classes and I want to organize them properly. Namespaces are best way to keep project clean and I believe that only automatization can actually help me) I wrote a script that adds a path based namespace to created C# file but there is a problem. For example, I have a namespace ProjectName.GUI and a class in the ProjectName namespace. When I'm trying to call GUI.Label() compiler throws error The type or namespace name Label' does not exist in the namespace MH.GUI'. Are you missing an assembly reference? May be you have recommendations how to organize my namespaces properly?

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tigertrussell · Mar 17, 2015 at 03:28 PM 0
Share

Can you post a small code example of how you are setting up your namespaces?

avatar image dr3th · Mar 17, 2015 at 03:56 PM 0
Share
  1. In Visual Studio the Namespaces are dynamically generated so the structure of namespaces are kept simple.

Each Project will have only 1 namespace.

When one creates a project eg "Controller", then all Classes generated in the project will live in the "Controller" namespace.

Does it look like this?

 //File one
 namespace ProjectName
 {
   public static class GUI
   {
     public static void Label()
     {
      
     }
   } 
 }
 
 //Some other File  
 namespace $$anonymous$$H
 {
     public class Something()
     {
           GUI.Label();
     }
 }


If so then you need to make a reference to the other namespace by adding the "using ProjectName;" reference.

Otherwise post your code and we can look at it here.

avatar image DontShooot · Mar 17, 2015 at 04:21 PM 0
Share

I don't like the way VS generating namespaces, so I wrote this

 using System;
 using System.IO;
 using UnityEngine;
 using UnityEditor;
 
 public class CSharpTemplate : UnityEditor.Asset$$anonymous$$odificationProcessor
 {
     public static void OnWillCreateAsset(string path)
     {
         path = path.Replace(".meta", string.Empty);
         path = path.Remove(0, "Assets/".Length);
         
         if (!path.EndsWith(".cs")) return;
         if (!path.StartsWith("scripts/")) return;
 
         string fullPath = Application.dataPath + "/" + path;
 
         int firstSlashIdx = path.IndexOf('/');
         string nameSpace = path.Remove(0, firstSlashIdx + 1);
 
         int lastSlashIdx = nameSpace.LastIndexOf('/');
         nameSpace = nameSpace.Remove(lastSlashIdx, nameSpace.Length - lastSlashIdx);
         nameSpace = nameSpace.Replace('/', '.');
 
         string result = string.Empty;
         bool namespaceGenerated = false;
         using (StreamReader sr = File.OpenText(fullPath))
         {
             while (!sr.EndOfStream)
             {
                 string line = sr.ReadLine();
                 if (line.Contains("namespace"))
                 {
                     return;
                 }
 
                 if (line.Contains("public class"))
                 {
                     result += "namespace " + nameSpace + Environment.NewLine + " {" + Environment.NewLine +
                               "//TODO: check if namespace correct";
                     namespaceGenerated = true;
                 }
 
                 if (namespaceGenerated)
                     result += "\t";
 
                 result += line + Environment.NewLine;
             }
 
             result += "}";
         }
 
         File.WriteAllText(fullPath, result);
         AssetDatabase.Refresh();
         
         Debug.Log("Namespace " + nameSpace + " was added to your script");
     }
 }
 

It's dirty, sorry)

avatar image DontShooot · Mar 17, 2015 at 04:26 PM 1
Share

"Each Project will have only 1 namespace." It's good way, but some times I want to "detail" namespace, for example I have few classes for weapon state machine. I think it's good to have

 namespace ProjectName.Weapon.Fsm
 {
     public class AnimationDependentState {}
 }

than

 public class WeaponFsmAnimationDependentState




1 Reply

· Add your reply
  • Sort: 
avatar image
4

Answer by ninjapretzel · Jan 14, 2016 at 11:43 PM

[tldr] For games, and for really any other kind of project, there are better methods of dealing with naming conflicts and code organization than just cramming everything into increasingly verbose namespaces.

Some general rules: -Only use namespaces if you are developing some kind of library code, and only if that code is something that is not used across the whole project. -Use classes as containers for classes/enums/interfaces/etc to avoid naming conflicts -If you have to have a naming conflict, use ailiasing to keep it from becoming a problem -Don't use namespaces when writing game scripts. [/tldr]

For video game development, the recommended usage of namespaces is: DONT.

Games are some of the most interconnected software, and it just further complicates things when you have to throw 20 using/import/whatever statements at the top of EVERY SINGLE SCRIPT. There's no advantage to having to declare imports when plenty of code files in a C# program (especially a game) will be requiring the same binaries to be loaded anyway.

The only time you can really get away with this is if you are writing code that only is ever used in a few places, or helper features you don't need everywhere, cluttering up your intellisense, or are writing something that gets compiled before/after your game code (Plugin/Editor scripts).

Normal game code shouldn't go in namespaces, especially if lots of stuff needs to interact with it. Any effects namespaces have on naming conflicts can normally be avoided by using internal classes rather than namespaces, for example:

 public class FancyText { 
     public class Settings {
         //Stuff goes here
     }
 }
 
 public static class Settings {
     //Game settings stuff here
 }
 
 public class DoesSomethingCool {
     public class Settings {
         //Stuff goes here too
     }
 }


This is also a better approach to something like naming in @DontShooot's reply.

 public class FSM {
     public class AnimationDependentState { }
 }

If you need to use code from somewhere else that is tucked away in a namespace, and you have a conflicting name, you can always alias it if needed.

 using Builder = System.StringBuilder;
 ///<summary> Wraps System.StringBuilder in order to add much needed + operators</summary>
 public class StringBuilder {
     public Builder str;
 
     //...tons of functions that keep all functionality of System.StringBuilder
 
     public static StringBuilder operator +(StringBuilder sb, string value) { return sb.Append(value); }
     //...etc....
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Can't use Namespaces with Mono and 1 class 1 namespace file 1 Answer

Problem with referencing namespaces C# 1 Answer

how to access script not derived from monobehavior ? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges