The question is answered, right answer was accepted
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
Answer by Cornelis-de-Jager · Jul 16, 2019 at 09:38 PM
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.
Follow this Question
Related Questions
How do switch scene with singleton pattern unity3d C# 2 Answers
When I should use a singleton and when just GetComponent? 0 Answers
Unkown Identifier: 'Manager' error when trying to use singletons 0 Answers
Game Manager singleton doesn't sync across the network 1 Answer
Unassigned reference exception 0 Answers