3
respostas

Dúvida sobre código com NullReferenceException

Estou tentando fazer um jogo da memoria no Unity e nessa parte do código surgiu esse erro e não consigo resolver:

using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.UI;

public class PictureManager : MonoBehaviour
{
    public Picture PicturePrefab;
    public Transform PicSpawnPosition;
    public Vector2 StartPosition = new Vector2(-2.15f, 3.62f);

    [Space] [Header("End Game Screen")]
    public GameObject EndGamePanel;

    public GameObject NewBestScoreText;
    public GameObject YourScoreText;
    public GameObject EndTimeText;

   [...]

    private bool _corutineStarted = false;

    private int _pairNumbers;
    private int _removedPairs;
    private Timer _gameTimer;

    void Start()
    {
        CurrentGameState = GameState.NoAction;
        CurrentPuzzleState = PuzzleState.CanRotate;
        PuzzleRevealedNumber = RevealedState.NoRevealed;
        _revealedPicNumber = 0;
        _firstRevealedPic = -1;
        _secondRevealedPic = -1;

        _removedPairs = 0;
        _pairNumbers = (int) GameSettings.Instance.GetPairNumber();

        _gameTimer = GameObject.Find("Main Camera").GetComponent<Timer>();
        
        [...]
private void DestroyPicture()
{
    PuzzleRevealedNumber = RevealedState.NoRevealed;
    PictureList[_picToDestroy1].Deactivate();
    PictureList[_picToDestroy2].Deactivate();
    _revealedPicNumber = 0;
    _removedPairs++;
    CurrentGameState = GameState.NoAction;
    CurrentPuzzleState = PuzzleState.CanRotate;
}

private IEnumerator FlipBack()
{
    _corutineStarted = true;

    yield return new WaitForSeconds(0.5f);

    PictureList[_firstRevealedPic].FlipBack();
    PictureList[_secondRevealedPic].FlipBack();

    PictureList[_firstRevealedPic].Revealed = false;
    PictureList[_secondRevealedPic].Revealed = false;

    PuzzleRevealedNumber = RevealedState.NoRevealed;
    CurrentGameState = GameState.NoAction;

    _corutineStarted = false;
}

private void LoadMaterials()
{
    var materialFilePath = GameSettings.Instance.GetMaterialDirectoryName();
    var textureFilePath = GameSettings.Instance.GetPuzzleCategoryTextureDirectoryName();
    var pairNumber = (int)GameSettings.Instance.GetPairNumber();
    const string matBaseName = "Pic";
    var firstMaterialName = "Back";

    for(var index = 1; index <= pairNumber; index++)
    {
        var currentFilePath = materialFilePath + matBaseName + index;
        Material mat = Resources.Load(currentFilePath, typeof(Material)) as Material;
        _materialList.Add(mat);

        var currentTextureFilePath = textureFilePath + matBaseName + index;
        _texturePathList.Add(currentTextureFilePath);
    }
    _firstTexturePath = textureFilePath + firstMaterialName;
    _firstMaterial = Resources.Load(materialFilePath + firstMaterialName, typeof(Material)) as Material;
}

void Update()
{
  if (CurrentGameState == GameState.DeletingPuzzles)
    {
        if(CurrentPuzzleState == PuzzleState.CanRotate)
        {
            DestroyPicture();
            CheckGameEnd();
        }
    }

  if (CurrentGameState == GameState.FlipBack)
    {
        if (CurrentPuzzleState == PuzzleState.CanRotate && _corutineStarted == false)
        {
            StartCoroutine(FlipBack());
        }
    }
    
  if (CurrentGameState == GameState.GameEnd)
    {
        if (PictureList[_firstRevealedPic].gameObject.activeSelf == false &&
            PictureList[_secondRevealedPic].gameObject.activeSelf == false &&
            EndGamePanel.activeSelf == false)
        {
            ShowEndGameInformation();
        }
    }
}

private bool CheckGameEnd()
{
    if (_removedPairs == _pairNumbers && CurrentGameState != GameState.GameEnd)
    {
        CurrentGameState = GameState.GameEnd;
        _gameTimer.StopTimer();
    }

    return (CurrentGameState == GameState.GameEnd);
}

private void ShowEndGameInformation()
{
    EndGamePanel.SetActive(true);
    YourScoreText.SetActive(true);

    var timer = _gameTimer.GetCurrentTime();
    var minutes = Mathf.Floor(timer / 60);
    var seconds = Mathf.RoundToInt(timer % 60);
    var newText = minutes.ToString("00") + ":" + seconds.ToString("00");
    EndTimeText.GetComponent<Text>().text = newText;
}

NullReferenceException: Object reference not set to an instance of an object PictureManager.ShowEndGameInformation () (at Assets/Scripts/PictureManager.cs:257) A linha 257 é essa EndTimeText.GetComponent().text = newText; e é como se não tivesse definida. Por favor, alguém sabe como resolver?

3 respostas

Oii, Maria! Tudo bem?

O erro NullReferenceException quer nos dizer que houve uma tentativa de acessar uma propriedade ou método em um objeto que não foi inicializado corretamente. Nesse caso, está ocorrendo na linha 257 do seu código, onde o objeto EndTimeText não está sendo encontrado ou não está definido.

Uma possível solução é verificar se o objeto EndTimeText está sendo atribuído corretamente no Unity. Revise se você arrastou o objeto EndTimeText para o campo correspondente no Inspector do Unity, na classe PictureManager.

Outro ponto importante é verificar se o objeto EndTimeText está ativo no momento em que você está tentando acessá-lo. Caso não esteja, você pode receber esse erro, o objeto está ativo antes de tentar acessar o componente Text.

Além disso, outra possível causa desse erro é se você estiver tentando acessar o componente Text em um objeto que não possui esse componente. Tenha certeza de que o objeto EndTimeText possui o componente Text corretamente adicionado a ele.

Espero que as sugestões sejam úteis para você! Continue interagindo no fórum compartilhando suas dúvidas, projetos e sugestões.

Bons estudos, Maria!

Boa tarde! Primeiramente, obrigada pela ajuda! Eu tentei verificar todas as suas informações mas ainda não consegui encontrar o erro, o objeto EndTimeText foi arrastado para o campo correspondente no Inspector do Unity, na classe PictureManager. Estou enviando algumas imagens do Unity para ver se verifica-se onde posso estar falhando CurrentTimePictureManager

Oi, Maria, tudo bem?

Vi que você tava usando o novo componente de texto o TextMeshPro então ao invés de usar GetComponent<Text>() (componente antigo) use GetComponent<TMP_Text>()

O .text entre outras coisas deve funcionar normal, bons estudos!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software