G
G
Gevorg2022-02-19 19:45:55
C++ / C#
Gevorg, 2022-02-19 19:45:55

NullReferenceException: Object reference not set to an instance of an object. What to do?

1 script.

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

public class XPMan : MonoBehaviour
{
    public  TextMeshProUGUI currentXPtext, targetXPtext, levelText;
    public  int currentXP, targetXP, level;

    public static XPMan instance;

    private void Awake()
    {
        if (instance == null)
            instance = null;
        else

            Destroy(gameObject);
    }

        private void Start()
        {
            currentXPtext.text = currentXP.ToString();
            targetXPtext.text = targetXP.ToString();
            levelText.text = level.ToString();
        }

        public void AddXP(int xp)
        {
        
            currentXP += xp;

            while (currentXP >= targetXP)
            {
                currentXP = targetXP - currentXP;
                level++;
                levelText.text = level.ToString();

            }

            currentXPtext.text = currentXP.ToString();
        }
}


2 script.

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

public class PL : MonoBehaviour
{
    public void ButtonPressed()
    {
        Debug.Log("XPMan");
        Debug.Log("instanse");
        Debug.Log("AddXP");
;        XPMan.instance.AddXP(10);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2022-02-20
@vabka

Well so you explicitly specified that instance = null.

private void Awake()
    {
        if (instance == null)
            instance = null;
        else

            Destroy(gameObject);
    }

Set a normal value and everything will be ok.
But better think about the architecture, how best to get this instance.

G
Gevorg, 2022-02-19
@gevorg_265

when the button is clicked, an error occurs: NullReferenceException: Object reference not set to an instance of an object.
To be honest, I'm a beginner, I don't understand a lot

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question