Home > Enterprise >  Namespaces not being recognized
Namespaces not being recognized

Time:11-01

I have the following class

namespace _Scripts.EnemyStuff
{
    public class Enemy : MonoBehaviour, IDamagable
    {
    }
}

And then when I try to use the class Enemy I need to specify that it comes from _Scripts.EnemyStuff even if they share the same parent.

The following code doesn't detect the Enemy class. I need to specify EnemyStuff.Enemy in order to make it work.

namespace _Scripts.Managers
{
    public class EnemyManager : MonoBehaviour
    {
        public Enemy firstEnemyGO;
    }
}

Why is this happening? Also, why it doesn't work if I use

using Enemy = _Scripts.EnemyStuff.Enemy;

CodePudding user response:

In general you always have to exactly define which type you are referring to. I would rather see it the other way round and there are certain cases where c# already "knows" so you can omit namespaces or parts of them. Among those e.g.

  • If you have a using XYNamespace; you can now omit XYNamespace. when referring to types within it.
  • If your type is in the same namespace or a subnamesapce of it

See also namespaces

share the same parent

They do not really! Your namespace hierarchy looks like

_Scripts
|-- EnemyStuff
|   |-- Enemy
|
|-- Managers
    |-- EnemyManager
    

c# looks for the type recursive up in the parent path (_Scripts.Managers.XY or _Scripts.XY) bu doesn't bubble back down all possible sibling namespaces.

So yes in this structure you will need to provided the namespace and use e.g.

public EnemyStuff.Enemy firstEnemyGO;

the EnemyStuff actually can be found looking in the common parent namespace _Scripts so you can omit the _Scripts.


Either

using System;
using UnityEngine;
using Enemy = _Scripts.EnemyStuff.Enemy;

namespace _Scripts.Managers
{
    public class EnemyManager : MonoBehaviour
    {
        public Enemy firstEnemyGO;
    }
}

or

using System;
using UnityEngine;

namespace _Scripts.Managers
{
    using Enemy = EnemyStuff.Enemy;
    
    public class EnemyManager : MonoBehaviour
    {
        public Enemy firstEnemyGO;
    }
}

or

using System;
using UnityEngine;

namespace _Scripts.Managers
{
    public class EnemyManager : MonoBehaviour
    {
        public EnemyStuff.Enemy firstEnemyGO;
    }
}

work perfectly fine for me

  • Related