Search Unity

Negating Searches

Discussion in 'Scripting' started by Gabe-Tucker, Nov 27, 2015.

  1. Gabe-Tucker

    Gabe-Tucker

    Joined:
    Nov 26, 2015
    Posts:
    94
    Code (CSharp):
    1. void Update ()
    2.     {
    3.         if (!GameObject.Find ("Space Ship Object"))
    4.         {
    5.             Invoke ("reload", 2.0f);
    6.         }
    7.     }
    8.  
    9.     void reload()
    10.     {
    11.         Application.LoadLevel(Application.loadedLevel);
    12.     }
    When the Space Ship Object gets destroyed, it doesn't activate (or invoke) the reload function, while it does if I'm not negating the 'if' statement. Please help.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    hate to say it, but this is completely the wrong way to go about this.

    You're checking for something to have been destroyed every frame, you're using find in all of those checks (which is a poor performance method). And if it did work for 2 seconds there are going to be invoke calls stacking up, which admittedly isn't a huge issue since the loadlevel will kill all those after the first, but still.

    Far better to have the thing being destroyed drive this rather than checking every frame. Check out the "OnDestroy" function.
     
    DeathQuake, Kiwasi and BenZed like this.