Design Patterns (Singleton Issue)


I’m asking this type of questions a lot, I guess that’s the best way of learning.

Here is the issue:

I’ve converted all of my project to C# from Unity Script, now, I didn’t check if everything was working until I converted all of my scripts.

I’ve tried to attach my new C# scripts to Empty GameObjects (that will take care of stuff) and I received an error, that these classes has no MonoBehaviour and it needed to inherit from it, in order to attach to GameObjects.

So what I did, was simply to inherit from MonoBehaviour to these classes, but, and here’s the catch, I somehow received an error that says I can’t return “new” MonoBehavior objects to other classes (scripts or objects), why is that? well here is why:

What I did, was to create a “FactoryObject” in order to return objects and classes as Singletons (like HUD or Particle Managers and so on).

Part of the factory script:

//This will return the AudioControl object.
		static AudioControl ac;
    	public static AudioControl GetAudioControl()
   			if(ac == null)
    			ac = new AudioControl();
   			return ac;
		//This will return the ParticleControl object.
		static ParticleControl pc;
    	public static ParticleControl GetParticleControl()
   			if(pc == null)
    			pc = new ParticleControl();
   			return pc;

and on and on…

Now I received plenty of errors telling me I can’t create a “new” out of a “MonoBehaviour” class, only AddComponent.
Well I personally have no idea how to convert my singleton classes in a way that it will be returned for every class as components (and single components of course, I don’t want to create multiple un-related components, of course that’s the main idea of singleton).

I need to return these classes in a way that I could reach each of these classes methods/functions, if they will be returned as Objects or GameObjects, then I could only use “SendMessage” which I dislike this option and try to avoid using it.

Otherwise I would have just get them as GameObjects for every script, but again, I don’t want this option, since it’s very restricted and not effective.

Thank You for your replies!

Îf a class is derived from MonoBehaviour and you want to use it as singleton, i usually use this:

public class ParticleControl : MonoBehaviour
    private static ParticleControl m_Instance = null;
    public static ParticleControl Instance
            if (m_Instance == null)
                m_Instance = (ParticleControl)FindObjectOfType(typeof(ParticleControl));
                if (m_Instance == null)
                    m_Instance = (new GameObject("ParticleControl")).AddComponent<ParticleControl>();
            return m_Instance;