0

Its just a question that bugs me on Unity.

We often use Singleton objects like game managers and so and there are two ways to go for this.

One is to use a Singleton.cs c sharp class as follows:

using System;
using System.Linq;
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    static T instance;

    DateTime BirthTime;

    public static T Instance
    {
        get
        {
            if (instance == null)
                Initialize();

            return instance;
        }
    }

    private void Awake()
    {
        BirthTime = DateTime.Now;
    }

    public static void Initialize()
    {
        if (instance == null)
            instance = FindObjectOfType<T>();
    }
}

And then derive our GameManager As

GamaManager : Singleton<GameManager>

In popular opinion, this method is CPU consuming, particularly on mobile as Unity has to iterate through hierarchy of so many objects for using the Initialize method mentioned in singleton.

A simpler approach is to create private instance and initialize it in Start or Awake as:

GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    void Start()
    {
        Instance = this;
    }
}

But I think, its like writing same code again and again. Can anybody suggest a cleaner approach to this?

1
  • I can only think of one other way. Using GetComponent<T>() instead of FindObjectOfType<T>() Commented Sep 18, 2017 at 19:49

1 Answer 1

1

I'm not sure what you want exactly, but in singleton pattern I prefer make a main class like GameManager and set it as a singleton class by using this piece of code:

static GameManager _instance;
    public static GameManager instance {
        get {
            if (!_instance) {
                _instance = FindObjectOfType<GameManager>();
            }
            return _instance;
        }
    }

Or the piece of code that you wrote, after that define variables according to other sub managers type and access to them by GameManagersingleton.

For example:

public BulletManager myBulletManager;

and use it like this:

GameManager.instance.myBulletManager.Fire();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.