@gevorg_265

NullReferenceException: Object reference not set to an instance of an object. Что делать?

1 скрипт.
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 скрипт.

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);
    }
}
  • Вопрос задан
  • 238 просмотров
Пригласить эксперта
Ответы на вопрос 1
vabka
@vabka Куратор тега C#
Токсичный шарпист
Ну так ты сам явно указал, что instance = null.
private void Awake()
    {
        if (instance == null)
            instance = null;
        else

            Destroy(gameObject);
    }

Задай нормальное значение и всё будет ок.
Но лучше подумай над архитектурой, как лучше получать этот экземпляр.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы