The question is answered, right answer was accepted
Referencing monobehaviour singleton from a non-monobehaviour class?
Hey I'm getting a NullReferenceException from this line of code:
List<Trait> possibleTraits = new List<Trait>(TraitDatabase.Instance.traits);
That line is called in a class Character, which does not derive from monobehaviour, whilst TraitDatabase is a script that does inherit from monobehaviour.
This is the script for TraitDatabase:
public class TraitDatabase : MonoBehaviour
{
public static TraitDatabase Instance { get; private set; }
public Trait[] traits;
public void Awake()
{
SetSingleton();
}
void SetSingleton()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
I have set the size for the Trait array in the inspector for the TraitDatabase script and filled it with ScriptableObjects Trait. So I'm fairly certain that that isn't what is causing this error. Is it possible that this error is related to monobehaviour?
Answer by Asaioki · May 30, 2020 at 12:09 PM
Turns out that the problem was that the line throwing the error was called in the Awake of some class, whilst as you can see, in the TraitDatabase, the singleton is also being set in Awake. Moving the call of this character class line to a start method solved it.
Follow this Question
Related Questions
NullReferenceException: Object reference not set to an instance of an object in Singleton class. 1 Answer
NullReferenceException: Object reference not set to an instance of an object error 0 Answers
What is going on with null reference checks recently? 0 Answers
Singleton ScriptableObject unable to Find itself, returns null 2 Answers
Alternative to singletons 0 Answers