Question about using namespaces

Hi there,

In the course you create a namespace RPG.Movement and add it in the playerControler.cs

Below in the code you use GetComponent().MoveTo(hit.point); but you have the RPG.Movement namespace. does the GetComponent become obsolete when you add the namespace RPG.Movement ?

using RPG.Movement;
using UnityEngine;

namespace RPG.Control
{
    public class PlayerControler : MonoBehaviour 
    {
        private void Update() 
        {
            if (Input.GetMouseButton(0))
            {
                MoveToCursor();
            } 
        }

        private void MoveToCursor()
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            bool hasHit = Physics.Raycast(ray, out hit);
            if (hasHit)
            {
                GetComponent<Mover>().MoveTo(hit.point);
            }
        }

    }
}

No, because the namespace has only give you access to the Mover component. You still have to locate the Mover component on your character.

Without the using RPG.Movement, the script would be unable to see the Mover component at all… the compiler will throw an error.

Ok, So you use the namespace because the cs file you want to acces is in another directory. If it was in the same directory a namespace would not be necessary. However you can’t put all the cs files in one directory because if the project got to big you would lose your overview.

So you use namespaces to get your files organized?

It’s not just about the files, it’s also about the classes. Namespaces allow you to

  • Reuse class names, and avoid naming conflicts
  • Group similar classes together (Combat related classes in RPG.Combat, Controller related classes in RPG.Control, etc)
  • Avoid cross dependencies between namespaces, so you can avoid RPG.Combat depending on RPG.Movement and RPG.Movement also depending on RPG.Combat.

You can make the namespace structure match your directory structure (that’s how we’ve done it in the course), or you can still keep all the files in the same directory (strongly recommend against that) and still put different groups of files in their own namespace.

1 Like

Ah ok I understand now.

Thank you so much for the extra information. I’m really enjoying the course.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms