How to use namespaces?

I can find little to no useful information to namespaces. I need to reference variables in my managerscript alot and my whole structure is a very confusing and complicated cobweb of references, so I thought I have a bright idea and turn this class into a namespace, something like this:

namespace example {
    public class Something : Monobehaviour
    {
         public float numberA;
    }
}

and from another script, I thought I could simply access the variables via:

using example;

public class SecondScript : MonoBehaviour
{
    Something st;
    float numberZ;

   private void Start
   {
      numberZ= st.numberA;
      //numberZ = numberA not working either
   }
}

which turns into a NullReferenceException error!? So… me very confused…

Namespaces are purely for code organisation.

You still need a concrete reference to other instances as per normal. In your second code’s case, Something st; is never assigned hence being null.

1 Like

I dont think namespaces are what you are looking for.

Namespaces are used so you can safely use class names without overlap with other plugins or unity classes.

E.g

Namespace SpaceA
{
   Class ClassA
   {
   }
}

Namespace SpaceB{
   Class ClassA
   {
   }
}

Class ClassB
{
   SpaceA.ClassA var1 = new SpaceA.ClassA();
   SpaceB.ClassA var2 = new SpaceB.ClassA();
}

What you are looking for is the singleton pattern, which is just a fancy term for a class with a singular instance.

The simplest way to implement it in unity is as follows:

Public class Something : MonoBehaviour
{
   Static Something m_instance;
   Public int TestVar;

   void Awake()
   {
      m_instance = this;
   }

   Public static Something GetInstance()
   {
      return m_instance;
   }
}

//to use it
class OtherClass : MonoBehaviour
{
   Something m_something;

   void Start()
   {
      //safe to grab here since instance is set in somethings awake
      m_something = Something.GetInstance();
      m_something.TestVar = 5;
   }
}

Something needs to be placed on an object in your scene & its only safe to use the GetInstance after Something Awake has been called. Thats why OtherClass does it in Start.

Hmmm, okay, thanks, looks like I completely misunderstood what namespace are there for… I knew about singletons but never used them, since my projects aren’t big. well I guess it’s time to use them anyway.
Edit: I still get NullReference Errors on some of my scripts, which apparently can’t find the singleton… no clue why but I will glue something together… somehow…
Edit2: Those scripts use onEnabled, that seems to be the issue.

1 Like