- Home /
C# custom getter and setter question
This works:
public static class ScoreStorer{
public static int highScore {get;set;}
public static int score {get;set;}
}
but when i try to write a custom one that checks if high score needs to be replaced, it gives a stack error:
public static class ScoreStorer{
public static int highScore {get;set;}
public static int score
{
get{return score;}
set
{
if(score > value)
highScore = score;
score = value;
}
}
What did i do wrong?
Comment
Best Answer
Answer by $$anonymous$$ · Apr 30, 2012 at 07:53 AM
The problem is that your set is recursive.
score = value;
calls the setters, which calls the setter, which calls the setter, etc...
You should do something like this :
private static int score;
public static int Score
{
get{return score;}
set
{
if(score > value)
highScore = score;
score = value;
}
}
and use Score anywhere else in your scripts.
Your answer
Follow this Question
Related Questions
Can I expose public field with getter-setter? 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do I access "gameObject" in a named class? 1 Answer
Implementing Setter/Getter 0 Answers