Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
24
Question by Olie · Mar 25, 2010 at 05:28 PM · gameobjectdestroy

How to detect if a GameObject has been destroyed?

I have a script that does something like this (psuedo-code-ish):

 var spawnedThing : GameObject;
 
 function Update()
 {
    if (whatever)
    {
       if (!spawnedThing || spawnedThing.isDestroyed)
           spawnedThing = InstantiateObject(...);
 
       spawnedThing.enabled;
    }
    else
    {
       if (spawnedThing && !spawnedThing.isDestroyed)
           spawnedThing.enabled = false;
    }   
 }


My question is: how do I determine if spawnedThing has been destroyed? That is, my spawn script wants to...


  1. Spawn something if there isn't already one.

  2. Enable/disable the spawned thing based on condition (eg, if player is too far away to notice.)

  3. Keep track of whether this one has been destroyed (i.e., player beat it up) and spawn a new one, if so.


When the GameObject is destroyed, does my variable go to null? Or do I have a pointer to a dead object? What's best-practice, here?


Thanks!

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image pracio · Jun 26, 2018 at 01:28 PM 0
Share

i think the best way to do so is to use if(spawnedThing),the best way is to use if(spawnedThing) to check if it's null

3 Replies

· Add your reply
  • Sort: 
avatar image
42
Best Answer

Answer by KvanteTore · Mar 25, 2010 at 06:05 PM

After an object is destroyed, an equality check with null will return true. The variable does not go to null, you can still call GetInstanceID() on it, but the "==" operator is overloaded and behaves as expected.


I believe the following would do the trick

 var spawnedThing : GameObject;
 
 function Update()
 {
    if (whatever)
    {
       if (spawnedThing == null)
           spawnedThing = InstantiateObject(...);
 
       spawnedThing.enabled;
    }
    else
    {
       if (spawnedThing != null)
           spawnedThing.enabled = false;
    }   
 }


Edit: However, if you do this often, it might be a better idea to go easy on the garbage collector and reuse the objects. Instead of Destroying the spawnedThing when it gets killed, you can disable it and re-enable it whenever necessary. See this question for more details.


Edit2: If don't want to poll every frame, you could implement the OnDisable function in a component on spawnedThing. See this forum thread for more details on that.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Olie · Mar 26, 2010 at 03:06 AM 0
Share

Ah, that's what I was wondering. Vote-up for direct answer, but I'm still wondering how to implement Eric's less-CPU-intensive see$$anonymous$$g solution.

avatar image frankrs · Feb 14, 2013 at 11:46 PM 0
Share

this dosent work

avatar image _MGB_ · Mar 03, 2014 at 10:30 AM 3
Share

Note: GameObjects get destroyed at the end of the current frame by default (unless you choose the immediate option, which is not advisable). Therefore tests against null will not return true until the next frame.

avatar image RossRH · Jan 08, 2018 at 08:52 AM 1
Share

Pretty confusing overload when debugging.

avatar image PanzerPotato · Apr 02, 2018 at 07:17 PM 0
Share

Using if (something == null) still returns null for me when "something" is destroyed...

avatar image
7

Answer by Eric5h5 · Mar 25, 2010 at 06:25 PM

Instead of polling every frame whether the object is destroyed, it's probably better just to have a callback which the object calls when it's destroyed.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Olie · Mar 26, 2010 at 03:05 AM 0
Share

That would indeed be better, but then what's the "you're about to be destroyed" function? Is there OnDestroyed() or some such? What I'm looking for in particular is for a function to be called any time anything destroys the object for any reason, without the fragility of requiring all destroyers to call theObject.Send$$anonymous$$essage("YoureAboutToBeDestroyed")

avatar image Eric5h5 · Mar 26, 2010 at 09:32 AM 2
Share

@Olie: There's OnDisable(), which isn't quite OnDestroy(), but can often be used as a substitute.

avatar image Olie · Mar 26, 2010 at 02:08 PM 2
Share

@Eric5h5: To be clear, are you saying that, whenever an object is destroyed, it is sent the message OnDisable() just before destruction?

avatar image KvanteTore · Mar 26, 2010 at 05:54 PM 1
Share

Yes, but the OnDisable() method is also called whenever the object is disabled. See this forum thread: http://forum.unity3d.com/viewtopic.php?p=274449&sid=c77bf5738b6b908a76dc4bd09e4b2ddc

avatar image dCalle · Nov 02, 2016 at 01:53 PM 0
Share

smart move, thanks boy ;-) (Guess the first nice thing I said in here^^ am getting better it seems^^)

avatar image
6

Answer by sindrijo · Jul 06, 2015 at 10:41 AM

Hi, I was also in the situation where I needed to know if a game object had been destroyed as opposed to the reference actually being null because I was running some code in OnDisable(), this is the solution I ended up with to test if a game object has been destroyed:

 public static class GameObjectExtensions
 {
         /// <summary>
         /// Checks if a GameObject has been destroyed.
         /// </summary>
         /// <param name="gameObject">GameObject reference to check for destructedness</param>
         /// <returns>If the game object has been marked as destroyed by UnityEngine</returns>
         public static bool IsDestroyed(this GameObject gameObject)
         {
             // UnityEngine overloads the == opeator for the GameObject type
             // and returns null when the object has been destroyed, but 
             // actually the object is still there but has not been cleaned up yet
             // if we test both we can determine if the object has been destroyed.
             return gameObject == null && !ReferenceEquals(gameObject, null);
         }
  }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers

How to Destroy Game Object In All Clients in Photon Network 0 Answers

Destroy all GameObjects EXCEPT some... 2 Answers

Why won't my script load? 1 Answer

Add and destroy instantiated gameobject in linkedlist C# 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges