0

as it is possible to check a GameObect for its existence (or instantiation) like this,:

GameObject x = new GameObject();
if(x){ 
   Console.Writeline("Instantiated GO");
}else{
   Console.Writeline("Not instantiated GO");
}

how do i check a Object of my own class for existence/instantiation ? I just get the error, that it could not be converted to bool.

My Question: How can I check objects of my own class like the GameObjects in Unity as shown in the code above ?

How do i fix this ? Is it Unity specific ?:

class myClass{
   public myClass(){ //Construcutor}
   public void createAndCheckClassObject(){
      myClass y = new myClass();
      if(y){
         Console.Writeline("Instantiated object");
      }else{
         Console.Writeline("Not instantiated object");
      }
   }
}
  • Compare it against `default(myClass)` (null) or implement a bool [operator overload.](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/overloadable-operators) – Scott Sep 05 '17 at 20:56
  • It is unlikely that a `new`-ly created object can be `null`. – Xiaoy312 Sep 05 '17 at 20:58
  • For sure - often in Unity these kinds of conditions are used to check if a parameter has been set or if some other kind of operation succeeded. – Scott Sep 05 '17 at 20:59
  • `GameObject` may have implemented an `implicit bool(GameObject)` operator to behave like that based on the initialization state, but not `myClass`. – Xiaoy312 Sep 05 '17 at 21:02
  • Don't do this. If you want check if some property of that object is true, (say, if it's been initialized) then have an `Initialized` property that you check. It makes no sense to write `if(y)` where `y` isn't inherently a boolean value. Don't make the same mistake that the author of `GameObject` made. – Servy Sep 05 '17 at 21:03
  • Sure, but i want to know whats behind this feature^^ –  Sep 05 '17 at 21:03
  • @louis12356 can you test this: `if (y.scene.name)` – Xiaoy312 Sep 05 '17 at 21:07
  • See duplicate for what's behind this feature. – Programmer Sep 05 '17 at 21:09
  • 1
    Ah, thank you - thats what i was looking for. –  Sep 05 '17 at 21:14

1 Answers1

0

Compare it to "null"

if (obj == null)
{
   //do something
}
  • I edited my post with the real question - sorry. –  Sep 05 '17 at 21:00
  • C# treats objects much like references in other C-based languages. When comparing objects it's comparing the exact object instance (in memory). Thus, comparing your object to null will tell whether there's an instance. The "if" statement is looking for a boolean comparison or result. It's likely that the Unity object has a direct conversion to "bool" within its definition, if your code executes properly as written. – Scott Willbanks Sep 05 '17 at 21:09