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?
GetComponent<T>()instead ofFindObjectOfType<T>()