0

I have a UI class with singleton and PresentGenerator, the class where I have my method.

public class UI : MonoBehaviour
{
private static UI _instance;
public static UI Instance { get { return _instance; } }

public PresentGenerator presentGenerator;

private void Awake()
{
    if (_instance != null && _instance != this)
    {
        Destroy(this.gameObject);
    }
    else
    {
        _instance = this;
    }
}
}

Here is what inside my PresentGenerator class

public class PresentGenerator : MonoBehaviour
{

public void CreatePresent()
{
    Instantiate(Present, new Vector3(Random.Range(-99,100), Random.Range(-54,55), 100), Quaternion.identity);
}
}

When I call this method within the PresentGenerator class, everything works perfect, however when I call it from other classes, for example, the enemy coin collector class:

public class EnemyCoinCollector : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
    if(other.CompareTag("Present"))
    {
        Destroy(other.gameObject);
        UI.Instance.presentGenerator.CreatePresent();
    }
}
}

I get the NullReferenceException: Object reference not set to an instance of an object. I can not figure out what is wrong. Please, help me out

Tim Markin
  • 19
  • 3
  • Is your UI class somewhere attached to something in the Scene? Otherwise `Awake` is never called and thus the instance never assigned... – derHugo Dec 07 '20 at 13:11

0 Answers0