Correct IsValid usage?

Started by Raubhamster · 4 months ago · 4 replies · 119 views

edited 4 months ago#1
Raubhamster
Member
JoinedFeb 2025 Posts16 Score95
https://sbox.game/dev/doc/code/code-basics/is-valid


I understood that you should use IsValid instead 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?
#2
Omjihn
Member
JoinedMar 2026 Posts20 Score855
Hi there !

IsValid() is a method that return a bool, and should be called like this : Target.IsValid()

if (Target.IsValid), will always return True cause 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())


#3
Raubhamster
Member
JoinedFeb 2025 Posts16 Score95
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?

#4
Omjihn
Member
JoinedMar 2026 Posts20 Score855
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.
#5
Daryl Winters
Member
JoinedMay 2021 Posts38 Score2,065
if (Target.IsValid), will always return True cause you are asking if the method exist. 


Not really,if (Target.IsValid) does not reffer to the method IsValid() but  IsValid is a property defined by the IValid interface and can be implemented differently by derived classes (for exemple in Component IsValid => this.GameObject != null && this.Scene != null;)


The documentation states that
IsValid() returns false when the object is null; otherwise, it returns the value of the object's IsValid property.

people
Log in to reply
You can't reply if you're not logged in. That would be crazy.