- Home /
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?
Can you post a small code example of how you are setting up your namespaces?
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.
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)
"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
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....
}