Please Help with Namespaces

Hello and … as a usual thanks for helping me. I am a newbie of course.

Well I am testing (trying to learn) “namespaces”.

My purpose was to set up a CountDown that returns “True” when it reaches zero.

In my “fantasies” I wanted to create different “CountDonws” objects … Please don’t make fun of me :smile: but I was thinking something like:

CountDown test = new CountDown();

namespace CD
{
    public class CountDown : MonoBehaviour
    {
        public bool countEnd = false;

        private IEnumerator StartCD(string messaggio, int maxSec, int minSec)
        {
            OsdManager.osdManager.bigMessage.text = messaggio + ": " + maxSec;
            yield return new WaitForSeconds(1);
            maxSec--;
            StartCoroutine(StartCD(messaggio, maxSec, minSec));
            if (maxSec < minSec) { StopCoroutine(StartCD(messaggio, maxSec, minSec)); OsdManager.osdManager.bigMessage.text = ""; countEnd = true; }
        }


        public void StartCountDown (string messaggio, int maxSec, int minSec)
        {
            StartCoroutine(StartCD(messaggio, maxSec, minSec));

        }
 
    }

So that adding “using CD” i could start … those countdowns and have a specific BOOL for specific coundowns:

If (test1.countEnd == true) …
if (test2.countEnd == true) …

But of course, this Idea seem not to work.

Is it simple to achieve this or I have to go back 35 years and start from my elementary School?

Oh… to create this script I just right clicked on my script folder …

Thanks again!!!

The namespace is not the issue here. Namespaces are used to organize code in logical groups and have no influence on the actual functioning of the code.
If you create a namespace named “CD”, you can indeed use it in other namespaces by referencing it via “using CD”. You should be able to create the CountDown class just fine then.

I’ve written the following without actually being behind Unity, so there might be a spelling error (notepad FTW!):

// CountDown class in CD namespace
namespace CD
{
    public class CountDown: MonoBehaviour
    {
        public bool countEnd = false;
       
        private void StartCD(string messaggio, int maxSec, int minSec)
        {
            // Reset count
            countEnd = false;

            OsdManager.osdManager.bigMessage.text = messaggio + ": " + maxSec;
            while (maxSec > minSec)
            {
                yield return new WaitForSeconds(1);       
                maxSec--;
                OsdManager.osManager.bigMessage.text = messagio + ": " + maxSec;
            }
            // Notify that we are finished
            countEnd = true;
        }
    }
}


// Other class using the CountDown class
using CD;

public class TestClass: MonoBehaviour
{
    private CountDown test1;

    void Awake()
    {
        test1 = new CountDown();
        test1.StartCD("Testint", 5, 0);
    }

    void Update()
    {
        if (test1.countEnd)
        {
            print("Countdown ended");
        }
        else
        {
            print("Countdown still counting");
        }
    }
}

Hi Alex! Thank for your help!

I had to change from “Private Void” to “Private IEnumerator” because of an error:
cannot be an iterator block because `void’ is not an iterator interface type
after that I did call that method but now I have this other error

You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all

Any tips?

Hey Feretro,

Try removing the “: MonoBehaviour” from the class definition. So make it like this:

namespace CD
{
    public class CountDown
    {
        public bool countEnd = false;
        ....

Hi Alex! Thanks! … If I do so … It does not accept “StartCoroutine” :frowning:

I’m guessing the StartCoRoutine is called from the WaitForSeconds function. You can replace that line by
“System.Threading.Thread.Sleep(1000);” and see if it works then.

yield return new WaitForSeconds(1);

// becomes

System.Threading.Thread.Sleep(1000);

I can’t help out much more without actually having Unity here to test things, sorry.

Hi,

MonoBehaviors can only exist if they are on a gameobject.

So instead of instantiating with new, try adding it to your existing gameobject like this:

// CountDown class in CD namespace
namespace CD
{
    public class CountDown: MonoBehaviour
    {
        public bool countEnd = false;
      
        private void StartCD(string messaggio, int maxSec, int minSec)
        {
            // Reset count
            countEnd = false;
            OsdManager.osdManager.bigMessage.text = messaggio + ": " + maxSec;
            while (maxSec > minSec)
            {
                yield return new WaitForSeconds(1);     
                maxSec--;
                OsdManager.osManager.bigMessage.text = messagio + ": " + maxSec;
            }
            // Notify that we are finished
            countEnd = true;
        }
    }
}

// Other class using the CountDown class
using CD;
public class TestClass: MonoBehaviour
{
    private CountDown test1;
    void Awake()
    {
        test1 = this.gameObject.AddComponent<CountDown>();
        test1.StartCD("Testint", 5, 0);
    }
    void Update()
    {
        if (test1.countEnd)
        {
            print("Countdown ended");
        }
        else
        {
            print("Countdown still counting");
        }
    }
}

Thank you Silicon! Your Solution is working!
Anyway with this solution I don’t even need to use namespace, right? I am a lot confused!

The most important think for me (for my purposes) is that I can create different countdowns using:

private CountDown testNumber1;
private CountDown testNumber2;
private CountDown testNumber3;

and then doing like

testNumber1 = this.gameObject.AddComponent()
testNumber2 = this.gameObject.AddComponent()
testNumber3 = this.gameObject.AddComponent()

and keep separate all their “bool values” :slight_smile:

Thanks to everyone is helping me

Namespaces can be thought of as just a way to organize your code.

You dont need to write your own code within a namespace.

It’s a pretty good habit to be in, though. If your code is in your own namespace then you don’t need to worry about whether or not your class names might collide with existing classes.

And if anyone comes across this and is considering writing code for an Asset Store package (or any code you plan to distribute to other Unity devs): If you don’t use namespaces on your project I curse you and your children for seven generations.

1 Like

Lol, don’t worry I namespace all of my code, here’s what I wrote today:

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//   ____ ___ _     ___ ____ ___  _   _   ____  ____   ___ ___ ____
//  / ___|_ _| |   |_ _/ ___/ _ \| \ | | |  _ \|  _ \ / _ \_ _|  _ \
//  \___ \| || |    | | |  | | | |  \| | | | | | |_) | | | | || | | |
//   ___) | || |___ | | |__| |_| | |\  | | |_| |  _ <| |_| | || |_| |
//  |____/___|_____|___\____\___/|_| \_| |____/|_| \_\\___/___|____/
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using UnityEngine;

namespace SiliconDroid
{
    //#############################################################################################################################
    //    CLASS: SD_Sound
    //#############################################################################################################################
    public class SD_Sound : SD_MonoBehaviour
    {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    CONSTANTS
        const string K_S_CLIP_PREFIX = "Sound/";
        const float K_F_DEF_VOLUME = 1.0f;
        const float K_F_DEF_PITCH = 1.0f;
        const int K_I_SOUND_SOURCES = 4;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    ENUMS
        public enum SOUND
        {
            CUTE_ANIMAL_VOICE,
            NEGATIVE_STINGER_01,
            POSITIVE_STINGER_01,
            POSITIVE_STINGER_02,
            POSITIVE_STINGER_03,
            POP_01,
            POP_02,
            POP_03,
            POP_04,
            POP_05,
            POP_06,
            POP_07,
            _COUNT,
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    WORKING DATA
        private class WORKING_DATA
        {
            public AudioSource[] acSrc = new AudioSource[K_I_SOUND_SOURCES];
            public AudioClip[] acClips = new AudioClip[(int)SOUND._COUNT];
            public int iAudioSourceNow;
        }
        WORKING_DATA v = new WORKING_DATA();

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //     _   _ _   _ ___ _______   __  _______     _______ _   _ _____ ____
        //    | | | | \ | |_ _|_   _\ \ / / | ____\ \   / / ____| \ | |_   _/ ___|
        //    | | | |  \| || |  | |  \ V /  |  _|  \ \ / /|  _| |  \| | | | \___ \
        //    | |_| | |\  || |  | |   | |   | |___  \ V / | |___| |\  | | |  ___) |
        //     \___/|_| \_|___| |_|   |_|   |_____|  \_/  |_____|_| \_| |_| |____/
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    AWAKE
        void Awake()
        {
            DontDestroyOnLoad(this.gameObject);
            this.name = "SD_SOUND";
            fnc_CreateAudio();
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //     ____  _   _ ____  _     ___ ____
        //    |  _ \| | | | __ )| |   |_ _/ ___|
        //    | |_) | | | |  _ \| |    | | |
        //    |  __/| |_| | |_) | |___ | | |___
        //    |_|    \___/|____/|_____|___\____|
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    PLAY
        public int fnc_Play(SOUND eSound, float fVolume = K_F_DEF_VOLUME, float fPitch = K_F_DEF_PITCH)
        {
            v.iAudioSourceNow = ++v.iAudioSourceNow % K_I_SOUND_SOURCES;
            v.acSrc[v.iAudioSourceNow].clip = v.acClips[(int)eSound];
            v.acSrc[v.iAudioSourceNow].volume = fVolume;
            v.acSrc[v.iAudioSourceNow].pitch = fPitch;
            v.acSrc[v.iAudioSourceNow].Play();
            return v.iAudioSourceNow;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    STOP
        public void fnc_Stop(int iAudioSource)
        {
            if(iAudioSource <0 || iAudioSource >= K_I_SOUND_SOURCES)
            {
                LOGW("AUDIOSOURCE OOB: " + iAudioSource);
                return;
            }

            if(v.acSrc[iAudioSource].isPlaying)
            {
                v.acSrc[iAudioSource].Stop();
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    RANDOM
        public int fnc_PlayRandomRange(SOUND eSoundLo, SOUND eSoundHi)
        {
            int iRange = eSoundHi - eSoundLo;
            int iSound = (int)eSoundLo + Random.Range(0, iRange);
            float fVolume = Random.Range(0.8f, 1.0f);
            float fPitch = Random.Range(0.8f, 1.2f);
            return fnc_Play((SOUND)iSound, fVolume, fPitch);
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //     ____  ____  _____     ___  _____ _____
        //    |  _ \|  _ \|_ _\ \   / / \|_   _| ____|
        //    | |_) | |_) || | \ \ / / _ \ | | |  _|
        //    |  __/|  _ < | |  \ V / ___ \| | | |___
        //    |_|   |_| \_\___|  \_/_/   \_\_| |_____|
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    SETUP
        void fnc_CreateAudio()
        {
            for(int iSrc = 0; iSrc < K_I_SOUND_SOURCES; iSrc++)
            {
                v.acSrc[iSrc] = fnc_CreateAudio_Source();
            }

            for (SOUND eSound = 0; eSound < SOUND._COUNT; eSound++)
            {
                string sClip = K_S_CLIP_PREFIX + ("" + eSound).ToLower();
                v.acClips[(int)eSound] = (AudioClip)Resources.Load(sClip);
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //    HELPER
        AudioSource fnc_CreateAudio_Source()
        {
            AudioSource cSrc = this.gameObject.AddComponent<AudioSource>();
            cSrc.spatialBlend = 0.0f;
            cSrc.playOnAwake = false;
            cSrc.volume = K_F_DEF_VOLUME;
            cSrc.pitch = K_F_DEF_PITCH;
            cSrc.loop = false;
            return cSrc;
        }
    }
}
1 Like