This is probably pretty simpel but I can’t get it to work. It isn’t even related to Unity but to C# syntax but hey, I know there are some C# guru’s here.
What I want to achieve is the following:
(this doesn’t work)
if (GameObject g = stack.Peek())
{
g.active = true;
}
So basicly, if the stack isn’t empty return the top gameobject from the stack and asign it to ‘g’.
What does work is:
It seems it cannot be done in C#, even though you can in other languages. It has to do with the fact that GameObject foo = null; is considered a statement, not an expression, and as such doesn’t return any value that you could use.
(Also, you live near me! Nice to know there are Unity users close-by :))
You cannot declare variable in if clause, but you can assing them:
object obj;
if ((obj = function()) != null)
thing is C# conditions don’t work as C ones. In C anything that has value of 0 is “false” and everything else is “true”. In C# it has to actually be a boolean value (good thing actually).
(obj = function()) → nullable object (ok in C)
((obj = function()) != null) → boolean (ok in C#)