problem with stackoverflow exception
Hello, I'am trying to make quiz game, but I'm getting trouble. I get StackOverflow Exception in my code. and the unity editor get force close when i trying to run the game. I will include link to my code and show the pict warning from unity.
here the link and pict 1. Picture Warning From unity editor console 2. Link quizUI Script link: https://drive.google.com/file/d/1In3zZ120tZdDrtExVuBB0eCBaR1hjHpF/view 3. Link quizManager Script link: https://drive.google.com/file/d/1-oS2nTwtLpAWt2vqKB8rP3rD8YExBJqV/view
Answer by streeetwalker · Sep 26, 2020 at 05:50 AM
you need backing fields for these getters:
public Text ScoreText
{
get
{
return ScoreText;
}
}
public Text TimerText
{
get => TimerText;
}
If you simply try to return the property name, which is what you are doing in the getter, you have created a recursive situation that never ends (e.g. TimerText has no way to get any value on its own - it is simply a wrapper for a value that you haven't created in your code ) Hence the stack overflow error.
To put it another way, getters and setters are really functions. Essentially you have a function that does this:
// function are placed on the stack when they are called,
// in your example the code does the below,
// and ends up calling the function ad infinitum, and the system runs out of stack space.
public ScoreText ScoreText(){
return ScoreText();
}
//whereas what you really want (in function form) is:
public string scoreText;
public string ScoreText(){
return scoreText;
}
// that is the same thing as a getter that works properly
So, if you want to use getters as you are trying to do, declare a backing field and give them values for each like you did with the other getters.
Answer by ArdienBR · Sep 27, 2020 at 02:55 AM
thanks for the solution, and im sorry because i'am newbie in a game developer
Hey @ArdienBR, mistakes are how everyone learns best - so no need to apologize for being new! Keep at it!
thanks $$anonymous$$r. for the support and teach me how to solve the problem