public static Player Ornek
{
get
{
if (Player.Ornek == null)
{
return Ornek;
}
else
{
Ornek = GameObject.FindObjectOfType();
}
return Ornek;
}
set
{
Ornek = value;
}
}
Hey Guys. I am trying to programming a platform game. Codes which was located top give me that error “StackOverflowException: The requested operation caused a stack overflow.” when ı push the keyboard to get jump the character. could you help me pls.
public static Player Ornek
{
get
{
if (Player.Ornek == null)
{
return Ornek;
}
else
{
Ornek = GameObject.FindObjectOfType<Player>();
}
}
}
(btw, code blocks make code much easier to read for the people helping you).
Look at line #6 above. You are accessing the very same getter you’re inside of! Player.Ornek is is going to go into the getter again, which is going to find Player.Ornek, and go into the getter again, and so on. What you probably want is a private backing field:
private static Player _ornek;
public static Player Ornek
{
get
{
if (Player._ornek != null)
{
return _ornek;
}
else
{
_ornek = GameObject.FindObjectOfType<Player>();
return _ornek;
}
}
}
And so on, the same applying to your setter as well.
Note: in the above, I also changed == null to != null because I suspect that’s what you intend to be doing: if there’s no ornek, find it and return it.
1 Like
This code is an infinite recursion, thus the stack overflow.
To explain, let’s say something asks for the current value of Ornek, this is what it does:
Get > if (player.ornek…
Okay, that needs to evaluate the get again, so…
Get > if (player.ornek…
Okay, that needs to evaluate the get again, so…
Get > if (player.ornek…
Okay, that needs to evaluate the get again, so…
and on and on and on it goes forever till the stack overflows.
You probably want another private variable like _ornek and use that to do this check instead,
something like this:
private static Player _Ornek
public static Player Ornek
{
get
{
if (Player._Ornek != null)
{
return Player._Ornek;
}
else
{
Player._Ornek = GameObject.FindObjectOfType<Player>();
}
return Player._Ornek;
}
set
{
_Ornek = value;
}
}
thank you so much for you support but ı’ve got one more failure. the character jump just one time. do you have any solution for that. thank you ahead.