Как исправить спам-рассылку программы Unity «NullReferenceException:» после завершения работы программы?C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Как исправить спам-рассылку программы Unity «NullReferenceException:» после завершения работы программы?

Сообщение Anonymous »

Я работаю над игрой, в которой используются сериализованные списки для отслеживания того, какие карты находятся в колоде, какие из них доступны для получения и т. д. Сама игра работает правильно, но при загрузке проекта Unity я получаю три таких нуля. ссылочные исключения, и когда игра закончилась (когда я нажимаю кнопку «Играть» в редакторе, чтобы остановить игру), я получаю спам с постоянно растущим списком этих ошибок.
Я понятия не имею, что происходит и что происходит отладка других проблем очень сложна, поэтому любая помощь будет оценена по достоинству. Код основного файла приведен ниже.

Код: Выделить всё

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using Unity.VisualScripting.Antlr3.Runtime.Tree;
using UnityEngine.SceneManagement;
using UnityEngine;
using UnityEngine.UI;
using System.Diagnostics.Tracing;

public class GameManager : MonoBehaviour {

public List availableCardPool = new List();
public List deck = new List();
public List playedCards = new List();
public List allCard = new List();
public Transform[] cardPoints;
public bool[] availableCardPoints;
public bool[] availableEventPoints;
public List selectableCardPoint;
public int handSize;
public TextMeshProUGUI deckSizeText;
public Card selectedCard;

[SerializeField] private List eventPoints = new List();
[SerializeField] private List events = new List();
[SerializeField] private Image selectionScreen;

private List selectedEvents;
private int enteredLevel = 1;
private bool cardSelection = false;
private bool eventSelection = false;
public List handCards = new List{null, null, null, null, null};
private List levelEvents = new List { null, null};
private int currentHighlight = 0;
private int currentEventHigtlight = 0;
public ScoreScript scoreScript;
public bool levelCompletion = false;
private bool endofLevelSelection = false;
private List selectableCards = new List();

public void DrawCard()
{
if (deck.Count == 0)
{
for (int j = 0; j < playedCards.Count; j++)
{
playedCards[0].hasBeenPlayed = false;
deck.Add(playedCards[0]);
playedCards.Remove(playedCards[0]);
}
}
if (deck.Count >= 1)
{
Card randCard = deck[UnityEngine.Random.Range(0, deck.Count)];

for (int i = 0; i < availableCardPoints.Length; i++)
{

if (availableCardPoints[i])
{
randCard.gameObject.SetActive(true);
randCard.handIndex = i;
handCards[i] = randCard;
randCard.transform.position = cardPoints[i].position;
availableCardPoints[i] = false;
deck.Remove(randCard);
return;
}
}
}
}

public void CardRound()
{

for (int i = 0; i < availableCardPoints.Length; i++)
{
DrawCard();
}
getCardChoice();

}
private void getCardChoice()
{
handCards[0].highlighted = true;
levelEvents[0].highlighted = true;
cardSelection = true;

}

private void Update()
{
if (cardSelection)
{

bool selected = false;
if (!selected)
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
if((currentHighlight + 1 ) < handCards.Count - 1)
{
bool finished = false;
for ( int i = currentHighlight + 1; i < handCards.Count;i++)
{
if (handCards[i] != null && !finished)
{
handCards[currentHighlight].highlighted = false;
currentHighlight = i;
handCards[currentHighlight].highlighted = true;
finished = true;
}
}

}
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
if ((currentHighlight - 1) > -1)
{
bool finished = false;
for (int i = currentHighlight - 1; i > -1;  i--)
{
if (handCards[i] != null && !finished)
{
handCards[currentHighlight].highlighted = false;
currentHighlight = i;
handCards[currentHighlight].highlighted = true;
finished = true;
}
}
}
}
if (Input.GetKeyDown(KeyCode.Return))
{
selected = false;
Debug.Log("Enter");
handCards[currentHighlight].selected = true;
cardSelection = false;

eventSelection = true;

}
}
}
else if (eventSelection)
{
bool selected = false;
if(!selected)
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
Debug.Log("Right arrow Pressed");
if ((currentEventHigtlight + 1)  -1)
{
bool finished = false;
Debug.Log("Left arrow fulfills check");
for (int i = currentEventHigtlight - 1; i > -1; i--)
{
if (levelEvents[i] != null && !finished)
{
if (levelEvents[currentEventHigtlight] != null)
{
levelEvents[currentEventHigtlight].highlighted = false;
}
currentEventHigtlight = i;
levelEvents[currentEventHigtlight].highlighted = true;
finished = true;
}
}
}
}
if (Input.GetKeyDown(KeyCode.Return))
{
selected = false;

handCards[currentHighlight].playAnimation = true;

int eventCount = 0;
getScore();

levelEvents[currentEventHigtlight].EventPlayedTo();
Debug.Log(levelEvents[currentEventHigtlight]);
levelEvents[currentEventHigtlight] = null;
handCards[currentHighlight] = null;

for (int i = 0; i < levelEvents.Count; i++)
{
Debug.Log("This is the list" + levelEvents[i]);
}

for (int x = 0; x < levelEvents.Count;  x++)
{
if (levelEvents[x] != null)
{
eventCount++;
Debug.Log("Eventcount: "+ eventCount);
}
}
Debug.Log("This is a test");
if (eventCount == 0)
{
Debug.Log("Eventcount shows no more events");
eventSelection = false;
levelComplete();

}
if (eventCount > 0)
{
Debug.Log("Eventcount showing remaining events");
eventSelection = false;
bool finished = false;

for (int i = 0; i < levelEvents.Count; i++)
{
if (levelEvents[i] != null && !finished)
{

currentEventHigtlight = i;
levelEvents[i].highlighted = true;
finished = true;
}
}

bool cardsFinished = false;

for (int i = 0; i < handCards.Count(); i++)
{
if (handCards[i] != null && !cardsFinished)
{
currentHighlight = i;
handCards[i].highlighted = true;
cardsFinished = true;
}
}

cardSelection = true;

}

}
}
}
else if (endofLevelSelection)
{
bool selected = false;
if (!selected)
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
if ((currentHighlight + 1) < selectableCards.Count - 1)
{
bool finished = false;
for (int i = currentHighlight + 1; i < selectableCards.Count; i++)
{
if (selectableCards[i] != null && !finished)
{
selectableCards[currentHighlight].highlighted = false;
currentHighlight = i;
selectableCards[currentHighlight].highlighted = true;
finished = true;
Debug.Log(selectableCards[currentHighlight].name);

}

}

}
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
if ((currentHighlight - 1) > -1)
{
bool finished = false;
for (int i = currentHighlight - 1; i > -1; i--)
{
if (selectableCards[i] != null && !finished)
{
selectableCards[currentHighlight].highlighted = false;
currentHighlight = i;
selectableCards[currentHighlight].highlighted = true;
finished = true;
}
}
}
}
if (Input.GetKeyDown(KeyCode.Return))
{
selected = false;
Debug.Log("Enter");
selectableCards[currentHighlight].selected = true;
endofLevelSelection = false;
addCardtoDeck();

}
}
}
}

private void getScore()
{
int requiredVariable = -1;
List requiredVariables = new List();
int score = 0;

for (int i = 0;  i < levelEvents[currentEventHigtlight].requirements.Count; i++)
{
if (levelEvents[currentEventHigtlight].requirements[i] == "e")
{
if (requiredVariable == -1)
{
requiredVariable = 0;
}
requiredVariables.Add(0);
}
else if (levelEvents[currentEventHigtlight].requirements[i] == "c")
{
if (requiredVariable == -1)
{
requiredVariable = 1;

}
requiredVariables.Add(1);
}
else if (levelEvents[currentEventHigtlight].requirements[i] == "t")
{
if (requiredVariable == -1)
{
requiredVariable = 2;

}
requiredVariables.Add(2);
}
else if (levelEvents[currentEventHigtlight].requirements[i] == "l")
{
if (requiredVariable == -1)
{
requiredVariable = 3;

}
requiredVariables.Add(3);
}
else if (levelEvents[currentEventHigtlight].requirements[i] == "r")
{
if (requiredVariable == -1)
{
requiredVariable = 4;

}
requiredVariables.Add(4);
}
else if (levelEvents[currentEventHigtlight].requirements[i] == "d")
{
if (requiredVariable == -1)
{
requiredVariable = 5;

}
requiredVariables.Add(5);
}

}
float multiplier;
if (levelEvents[currentEventHigtlight].era == handCards[currentHighlight].era)
{

multiplier = 1.5f;
}

else
{

multiplier = 1;
}

if (requiredVariables.Count == 1)
{
score = (int)Mathf.Ceil((levelEvents[currentEventHigtlight].baseScore * ((handCards[currentHighlight].stats[requiredVariable])) * multiplier )/ 100);

}

else if (requiredVariables.Count > 1)
{
List scores = new List();
for (int x = 0; x < requiredVariables.Count; x++)
{
int tempscore = (int)Mathf.Ceil((levelEvents[currentEventHigtlight].baseScore * ((handCards[currentHighlight].stats[requiredVariables[x]])) * multiplier) / 100);
scores.Add(tempscore);
Debug.Log(tempscore);
}

int totalscore = 0;

for (int i = 0; i < scores.Count; i++ )
{
totalscore += scores[i];

}

score = totalscore / scores.Count;
}

scoreScript.currentScore += score;
}

private void Start()
{
selectionScreen.gameObject.SetActive(false);
for(int i = 0; i < allCard.Count; i++)
{
if (allCard[i].era == enteredLevel)
{
deck.Add(allCard[i]);
}
else
{
availableCardPool.Add(allCard[i]);
}
}
LoadLevel(enteredLevel);
CardRound();
}

private void LoadLevel(int gameStage)
{
List possibleEvents = new List();
Event selectedEvent;
int selectedEra = gameStage; //1 - Ancient   2 - Renaissance   3 - Industrial   4 - World Wars  5 - Late 20th Century  6 - Modern

for (int i = 0; i < events.Count;  i++)
{
if (events[i].era == selectedEra)
{

possibleEvents.Add(events[i]);
}
}

if (possibleEvents.Count == 1)
{
selectedEvent = possibleEvents[0];
availableEventPoints[0] = false;
levelEvents[0] = selectedEvent;
selectedEvent.gameObject.SetActive(true);
Debug.Log(selectedEvents[0].name);
selectedEvent.transform.position = cardPoints[0].position;

}
else
{
for (int i = 0; i < levelEvents.Count(); i++)
{
bool placed = false;
for (int x = 0; x < availableEventPoints.Count(); x++)
{
if (!placed && availableEventPoints[x])
{
int myValue = UnityEngine.Random.Range(0, possibleEvents.Count);
selectedEvent = possibleEvents[myValue];
possibleEvents.Remove(selectedEvent);
availableEventPoints[x] = false;
levelEvents[x] = selectedEvent;
selectedEvent.gameObject.SetActive(true);
selectedEvent.transform.position = eventPoints[x].position;
placed = true;
}
}

}

}

int requiredScore = 0;
int maxScore = 0;
for (int i = 0; i < levelEvents.Count(); i++)
{
requiredScore += levelEvents[i].requiredScore;
maxScore +=  (int)(Mathf.Ceil(levelEvents[i].baseScore * 1.5f));
}

scoreScript.requiredScore = requiredScore;
scoreScript.maxScore = maxScore;
scoreScript.currentScore = 0;

}

void levelComplete()
{
if (scoreScript.currentScore >= scoreScript.requiredScore)
{
levelCompletion = true;
}

if (levelCompletion)
{

selectionScreen.gameObject.SetActive(true);
for(int i = 0; i < 3; i++)
{

Card cardOption = availableCardPool[UnityEngine.Random.Range(0, availableCardPool.Count)];
selectableCards.Add(cardOption);
availableCardPool.Remove(cardOption);
cardOption.transform.position = selectableCardPoint[i].position;
cardOption.gameObject.SetActive(true);
Debug.Log(cardOption.name);
currentHighlight = 0;
endofLevelSelection = true;

}

}
}

void addCardtoDeck()
{
if (deck.Count < 5)
{
deck.Add(selectableCards[currentHighlight]);
Debug.Log(deck[4].name);

}
}
}

Сначала я установил карты в инспекторе в доступные карты и колоду, а затем переместил их в зависимости от того, что происходит в игре. Казалось, Unity не нравилось, что эти списки пусты в конце, если их не было в начале. Затем я изменил его так, чтобы все карты находились в списке allCards и просто добавлялись в другие списки, но ошибка все равно возникает.
Моя главная проблема в том, что я понятия не имею, почему это происходит. выдавать ошибки ПОСЛЕ того, как игра закончилась - когда ни один из моих кодов больше не работает. Мне кажется, это как-то связано с тем, как Unity обрабатывает сериализованные поля, но я недостаточно знаю об этом, чтобы понять, как это исправить.

Подробнее здесь: https://stackoverflow.com/questions/784 ... -the-progr
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»