Correct IsValid usage?

Started by Raubhamster 5 posts 116 views

Reply on sbox.game
  1. edited May 2026 #1
    Raubhamster 95
    https://sbox.game/dev/doc/code/code-basics/is-valid

    image.png 72.52 KB

    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. #2
    Omjihn 855
    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. #3
    Raubhamster Started this 95
    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. #4
    Omjihn 855
    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. #5
    Daryl Winters 2,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.