Sunday, 7 November 2021

Unity Implementing Singleton

  Creating singleton objects can be very useful but you should  use it with some caution  first of all you need to make sure only one object is created in scene  and make sure it's needed for all scenes like audio/level changing exc

And Second important thing is don't make it a GOD mode class  and don't put everything in singleton classes

it will make your project more and more coupled and when it gets bigger you won't be able to manage it

there are several ways to create a singleton class but we will use it with a generic type so you can reuse it in any kind of project you like ;

Example is a simple level changing manager system like "GameManager"  when level completed loads the next level  and on next level loads next level again you dont have to  add this object in every level of the game



First of All our Generic "SingletonCreator" class ;


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingletonCreator<T> : MonoBehaviour where T:MonoBehaviour{

    private static T _instance;
    public static T instance
    {
        get
        {
         
            return _instance;
        }
        set
        {
            _instance = value;
        }
    }
    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(gameObject);
        }
        _instance = this.GetComponent<T>();
        DontDestroyOnLoad(_instance);
    }

}

And Our  GameManager Looks like this; (Don't forget to add this "MonoBehaviour" class to scene or you may get null exceptions)


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : SingletonCreator<GameManager>;
{
    public int LevelIndex = 0;
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("object created");
        
    }



    public void LoadnextLevel()
    {
        LevelIndex += 1;
        SceneManager.LoadScene(LevelIndex);
    }

    public int NextLevelIndex()
    {
        Debug.Log($"LevelIndex Current Value : {LevelIndex}");
        LevelIndex++;
        return LevelIndex;
    }

    
}

As you se GameManager,AudioManager exc can be easily made singleton you may implement this aproach for different game objects 

To call Any GameManager Method  wrote a Single ButtonClick script  this script calls 

GameManager And Loads Scene



using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ButtonClick : MonoBehaviour
{
    [SerializeField]
    Text buttonText;
    public void LoadNextScene()
    {
        GameManager.instance.LoadnextLevel();
    }

    public void IncreaseLevelText()
    {
        buttonText.text = GameManager.instance.NextLevelIndex().ToString();
    }
}

when you click button loads Nextlevel from GameManager.instance and second method increases levelIndex just for test out you may add a button on scene and bind this "ButtonClick" script and call NextLevel or IncreaseLevelText methods

Feel free to ask me any question you like

Happy Coding :)

No comments:

Post a Comment