x


How to detect in OnDestroy if scene is closing/game is being closed

Hello,

I have a question if there is a way to detect in the OnDestroy() function if the object is destroyed because the level is closing/game is closing.

I have an object (soldier) that is spawning other objects in some situations (health-bar etc.). In the soldier's OnDestroy() I also remove all objects that the soldier spawned (soldier keeps references). The code looks like this:

class Soldier{

    Transform m_CreatedObject = null;

    public void Updade()
    {
       if (something)
           m_CreatedObject = Instantiate(something);
    }

    public void OnDestroy()
    {
       if (m_CreatedObject  != null)
          Destroy(m_CreatedObject);
    }

}

When I close the editor I get the MissingReferenceException because Unity destroyed the m_CreatedObject before Soldier object when the game is closed. What can I do in this situation?

more ▼

asked Mar 06 '12 at 02:32 PM

mstruzyna gravatar image

mstruzyna
16 3 3 4

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

No, there isn't- but that's why the

void OnApplicationQuit()
{
    // do stuff here!
}

callback exists! Use this to destroy the sub-elements before the game would close, preventing the OnDestroy problems from occuring.

more ▼

answered Mar 06 '12 at 02:35 PM

syclamoth gravatar image

syclamoth
14.8k 7 15 80

Ehhh sorry. I was not aware of such callback. This will solve my problem. Thank you!

Mar 06 '12 at 11:32 PM mstruzyna

No need to apologise! That's what this site is for, after all.

Mar 07 '12 at 12:34 AM syclamoth
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x18

asked: Mar 06 '12 at 02:32 PM

Seen: 836 times

Last Updated: Mar 07 '12 at 12:34 AM