Can we use a Singleton here?

I turned my LevelLoader prefab into a singleton to make it reusable cross the game.

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

public class LevelLoader : MonoBehaviour
{
    public static LevelLoader instance;


    private void Awake()
    {
        SetUpSingleton();
    }

    private void SetUpSingleton()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(LoadGame());
    }

    // Update is called once per frame
    void Update()
    {
        
    }


    IEnumerator LoadGame()
    {
        yield return new WaitForSeconds(3);
        SceneManager.LoadScene("StartScreen");
    }
}

Good thinking. I had done the same thing myself, but instead opted to use Rick’s system as it seemed less error prone. I was worried that by using a singleton without an if-statement in start, that it may cause errors down the road if I was trying to test specific scenes later on, potentially throwing me back to the start screen.

Privacy & Terms