Stack Overflow error GetComponent
Hi all, I am encountering a stack overflow error, and I am very confused as to why this is happening. There is quite a lot going on but, I will try and explain what is going on as best as I can script by script. It might be a case that my whole architecture is wrong so please do let me know.
This a question-answer game with a countdown to give the game a second to fetch from a database of questions. The starting point is the button to start the game:
SceneLoader.cs
The key part of this script is this:
public void LoadSpeedPlay()
{
SceneManager.LoadScene(1);
mySessionManager.SetGameMode("SpeedPlay");
}
So when you click the button, the game mode for SessionManager.cs sets the private var game mode to the desired game mode (sorry it's a string, I know bad practice).
CountdownManager.cs
When the scene loads, but countdown starts. This what will fire off to start the game when it reaches 0. Below is the script. The error occurs, when it's about to say go, so it's somewhere in the else block.
public class CountDownManager : MonoBehaviour
{
TextMeshPro myTextMeshpro;
QuestionSpawner myQuestionSpawner;
TimerManager myTimerManager;
SessionManager mySessionManager;
int counter = 3;
void Start()
{
mySessionManager = FindObjectOfType<SessionManager>().GetComponent<SessionManager>();
myQuestionSpawner = FindObjectOfType<QuestionSpawner>().GetComponent<QuestionSpawner>();
myTimerManager = FindObjectOfType<TimerManager>().GetComponent<TimerManager>();
myTextMeshpro = GetComponentInChildren<TextMeshPro>();
myTextMeshpro.text = counter.ToString();
StartCoroutine(StartCountDown());
}
public IEnumerator StartCountDown()
{
for (int i = counter; i >= 0; i--)
{
if(counter > 0){
yield return new WaitForSeconds(1f);
counter--;
myTextMeshpro.text = counter.ToString();
} else
{
myTextMeshpro.text = "GO!";
mySessionManager.StartGame();
Destroy(gameObject, 1f);
}
}
}
}
We now head to Session Manager which is the script that I have been working on to manage most of what is going on in-game. Or at least monitor it.
SessionManager.cs
So in StartGame there is a Switch that checks what GameMode is set, and then plays the game according to what it needs. I.E. Speedplay timer counts up, Against the Clock timer counts down, so there needs to be someway to differentiate. We also set the isGameActive to true.
public class SessionManager : MonoBehaviour
{
public string currentGameMode = "";
private bool isGameActive = false;
private void Awake()
{
int numOfSessionManagers = FindObjectsOfType<SessionManager>().Length;
if(numOfSessionManagers > 1)
{
Destroy(this.gameObject);
} else
{
DontDestroyOnLoad(gameObject);
}
}
public void SetGameMode(string gameMode)
{
this.currentGameMode = gameMode;
}
public bool ReturnGameStatus()
{
return isGameActive;
}
public void StartGame()
{
isGameActive = true;
switch (currentGameMode)
{
case "SpeedPlay":
FindObjectOfType<QuestionSpawner>().GetComponent<QuestionSpawner>().StartQuestions();
FindObjectOfType<TimerManager>().GetComponent<TimerManager>().StartSpeedPlay();
break;
case "AgainstTheClock":
FindObjectOfType<TimerManager>().GetComponent<TimerManager>().StartSpeedPlay();
break;
default:
return;
}
}
public void EndGame()
{
isGameActive = false;
}
}
From here we go to QuestionSpawner.cs, where the questions are pulled from the database, create a question, answer, and wrong answer list, and also has a function that dispenses the next question on the list.
QuestionSpawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;
using TMPro;
public class QuestionSpawner : MonoBehaviour
{
[SerializeField] GameObject questionText;
[SerializeField] public List<string> questionList = new List<string>();
[SerializeField] public List<int> correctAnswers = new List<int>();
[SerializeField] public List<int> incorrectAnswers = new List<int>();
public int timerCounter = 3;
private int difficulty = 1;
[SerializeField] GameObject countDown;
SessionManager mySessionManager;
QuestionModel questions;
CountDownManager myCountDownManager;
AnswerChecker myAnswerChecker;
public int counter = 0;
public bool qActive = false;
private void Awake()
{
StartCoroutine(BuildQuestions());
}
private void Start()
{
myAnswerChecker = FindObjectOfType<AnswerChecker>().GetComponent<AnswerChecker>();
mySessionManager = FindObjectOfType<SessionManager>().GetComponent<SessionManager>();
}
public void StartQuestions()
{
SpawnQuestion();
myAnswerChecker.DisplayAnswers();
}
IEnumerator BuildQuestions()
{
string difficultyText = difficulty.ToString();
List<IMultipartFormSection> form = new List<IMultipartFormSection>();
form.Add(new MultipartFormDataSection("difficulty", difficultyText));
UnityWebRequest request = UnityWebRequest.Post("http://localhost/projectLearning/pullMathsQuestions.php", form);
request.useHttpContinue = false;
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log("Connection Failed");
}
else
{
questions = JsonConvert.DeserializeObject<QuestionModel>(request.downloadHandler.text);
CreateQuestionsList(questions);
}
}
private void CreateQuestionsList(QuestionModel qObj)
{
for (int i = 0; i < 12; i++)
{
questionList.Add(qObj.data[i].question);
correctAnswers.Add(int.Parse(qObj.data[i].answer));
incorrectAnswers.Add(int.Parse(qObj.data[i].wrongAnswer_1));
}
}
public void SpawnQuestion()
{
Vector3 startPos = transform.position;
int spawnAngle = Random.Range(-30, 30);
GameObject thisQuestion = Instantiate(questionText, startPos, Quaternion.Euler(0, 0, spawnAngle)) as GameObject;
thisQuestion.name = counter.ToString();
TextMeshPro myTextMesh = thisQuestion.GetComponent<TextMeshPro>();
myTextMesh.text = questionList[counter];
}
public void CheckQuestionList()
{
if(questionList.Count - counter <= 3)
{
StartCoroutine(BuildQuestions());
}
}
}
In answer checker, we are very simply getting the right and wrong answer from the question spawner game object, and then displaying them in the TMProUGUI buttons.
public void DisplayAnswers()
{
string wrongAnswer = myQuestionSpawner.incorrectAnswers[myQuestionSpawner.counter].ToString();
string correctAnswer = myQuestionSpawner.correctAnswers[myQuestionSpawner.counter].ToString();
int randomNum = Random.Range(0, 2);
if (randomNum == 1)
{
leftTextMeshPro.text = wrongAnswer;
rightTextMeshPro.text = correctAnswer;
} else{
leftTextMeshPro.text = correctAnswer;
rightTextMeshPro.text = wrongAnswer;
}
}
In TimerManager which is also being called in SessionManager.cs we are starting the relevant coroutine, depending on the game mode.
TimerManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro;
public class TimerManager : MonoBehaviour { private float totalSeconds = 0f; / private float seconds = 0; private float minutes = 0; private string secondsDisplay = ""; private string minutesDisplay = ""; /
/*TODO - FIX THE GAME MODE SO THAT THE GAME KNOWS WHETHER TO DEDUCT OR ADD SECONDS
private int gameModeIndex = 0;
*/
TextMeshProUGUI myTextMeshProUGUI;
SessionManager mySessionManager;
void Start()
{
myTextMeshProUGUI = GetComponent<TextMeshProUGUI>();
mySessionManager = FindObjectOfType<SessionManager>().GetComponent<SessionManager>();
}
void Update()
{
totalSeconds += Time.deltaTime;
myTextMeshProUGUI.text = Mathf.Floor(totalSeconds).ToString();
/* TODO - MAKE TIME DISPLAY CORRECTLY.
seconds = Mathf.Floor(totalSeconds) % 60;
minutes = Mathf.Floor(totalSeconds) / 60;
secondsDisplay = seconds < 10 ? (seconds.ToString("D").Length + 1).ToString() : seconds.ToString();
minutesDisplay = minutes < 10 ? (minutes.ToString("D").Length + 1).ToString() : minutes.ToString();
myTextMeshProUGUI.text = minutesDisplay + ":" + secondsDisplay;
*/
}
public void StartSpeedPlay()
{
StartCoroutine(DeductSecond(60));
}
public void StartAgainstTheClock()
{
StartCoroutine(AddSecond());
}
IEnumerator DeductSecond(int seconds)
{
totalSeconds = seconds;
do
{
yield return new WaitForSeconds(1f);
totalSeconds--;
myTextMeshProUGUI.text = totalSeconds.ToString() + "s";
}
while (totalSeconds > 0);
if(totalSeconds == 0)
{
mySessionManager.EndGame();
}
}
IEnumerator AddSecond()
{
totalSeconds = 0f;
do
{
yield return new WaitForSeconds(1f);
totalSeconds++;
myTextMeshProUGUI.text = totalSeconds.ToString();
}
while (mySessionManager.ReturnGameStatus() == true);
}
}
I think that's it. No idea why I am getting this issue. Please can anyone help?
Your answer
Follow this Question
Related Questions
How can I fix UnityEngine.Random.Range (Int32 min, Int32 max) Stack Overflow 0 Answers
Hi Everyone Please help me with Unity And Admob integration 0 Answers
StackOverflow on Instantiate 1 Answer
StackOverflow Problem when consistently checking a gameObject 1 Answer
StackOverflowException, cant find out how to fix it 0 Answers