Singleton Class

Hello, good to everyone. I’m trying to do a singleton class to use it as static, I’ve seen thousands of examples and they all come out the same but to me, for some reason it does not work for me.

Class Singleton

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

public class WorldGridGenerator : MonoBehaviour
{
    public static WorldGridGenerator instance = null;

    private void Awake()
    {
        singleton();
    }

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

    public static WorldGridGenerator Instance {
        get { return instance; }
    }


    public void generateGrid(GameObject gridCenter)
    {


    }
}

Class that invoke it

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

public class GridController : MonoBehaviour
{
    //para debug
    public bool playerContain;

    private void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            WorldGridGenerator.Instance.generateGrid(gameObject);
            playerContain = true;
        }
    }

    private void OnCollisionExit(Collision other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            playerContain = false;
        }
    }
}

Error:

NullReferenceException: Object reference not set to an instance of an object
GridController.OnCollisionEnter (UnityEngine.Collision other) (at Assets/Scripts/Ponce/GridController.cs:14)

Line 14 : WorldGridGenerator.Instance.generateGrid(gameObject);

Thanks to everyone

To fix your error you need to create an ingame object with your WorldGridGenerator attached.


Let me explain why, when creating a static class you can reference throught your code it looks like this normally:

public static class WorldGridGenerator {
	...
}

But since we are inheriting from MonoBehaviour we can’t instantiate static classes, only classes with static properties and functions.

public class WorldGridGenerator : MonoBehaviour {
	
	public static WorldGridGenerator instance = null;
	
	...
}

Meaning that if you want to call the WorldGridGenerator as you did in your code you will first need to instiate a object with an instance of WorldGridGenerator already on it.