Correct IsValid usage?
Reply on sbox.game-
https://sbox.game/dev/doc/code/code-basics/is-valid

image.png 72.52 KB
I understood that you should useIsValidinstead of null checking.
This gives me a null reference exception when target is not set:if (Target.IsValid && Target.Health > 0 ) {
This works:if (Target != null && Target.IsValid && Target.Health > 0 ) {
What am I missing here? -
Hi there !
IsValid()is a method that return a bool, and should be called like this :Target.IsValid()if (Target.IsValid), will always returnTruecause you are asking if the method exist.
You need to call it like this to check whether the object is valid or not :if (Target.IsValid()) -
Thank you very much!
I kinda feel stupid now. How did I not see the difference from the documentation and mine..
So, is there a way to mark an answer as solution? -
You're welcome !
No worries the only matter is that you get it now, and hopefully it will help others.
And I don't think you can mark any solution in this forum no. -
if (Target.IsValid), will always returnTruecause you are asking if the method exist.
Not really,if (Target.IsValid)does not reffer to the methodIsValid()butIsValidis a property defined by theIValidinterface and can be implemented differently by derived classes (for exemple in ComponentIsValid => this.GameObject != null && this.Scene != null;)The documentation states thatIsValid()returnsfalsewhen the object isnull; otherwise, it returns the value of the object'sIsValidproperty.