Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
This post has been wikified, any user with enough reputation can edit it.
avatar image
4
Question by kamil.slawicki · Jan 15, 2013 at 11:44 AM · gameobjecteditordeletecallbackondestroy

OnDestroy() callback in Editor upon deleting selected GameObject - del key

Hi there. I have a fallowing problem, I need to do some logic when a user deletes a GameObject in the scene. Ideally it should work at any time when the GameObject gets deleted in the editor, however I really need a callback upon pressing delete key. I have tried adding OnDelete() function to a script attached to this GameObject: that failed. I have also tried to execute the script in edit mode - that also failed. I guess I could add some messy logic to the update function and execute that in the editor, it unfortunately does not sound very clean. I am kind of stuck, please help.

Comment
Add comment
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

5 Replies

· Add your reply
  • Sort: 
avatar image
4
Best Answer Wiki

Answer by kamil.slawicki · Jan 15, 2013 at 12:02 PM

Ok, take it back. It turns out that I cannot spell destroy properly. Adding [ExecuteInEditMode] ensures that OnDestroy is being triggered properly in the editor.

Comment
Add comment · Show 3 · 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 paraself · Sep 01, 2013 at 11:33 AM 0
Share

Though it triggers OnDestroy() properly in Editor, yet it also triggers OnDestroy() when switching from editor to runtime after hitting Play button. Can anyone suggest a better solution which only detect gameobject deletion. $$anonymous$$y code sample:

 void OnDestroy(){
         if ((Application.isPlaying==false)&&(Application.isEditor==true)&&(Application.isLoadingLevel==false))
         Debug.Log(this.name + " is destroyed");
         
     }
avatar image Michael-Ryan paraself · Nov 03, 2016 at 08:43 AM 1
Share

Application.isLoadingLevel is now deprecated.

As a potential workaround, when OnDestroy is called while loading a level in the editor, Time.frameCount and Time.renderedFrameCount appear to always equal zero (0). The two Time properties appear to be greater than zero when manually deleting gameObjects in the editor.

avatar image Ash-Blue · Aug 22, 2017 at 08:23 AM 0
Share

This no longer appears to work with ScriptableObject(s) as of 5.6.2f1. OnDestroy never triggers, but events like Awake seem to trigger correctly. $$anonymous$$ight be a bug.

avatar image
1

Answer by Iq110 · Jun 30, 2020 at 10:35 AM

I found that this method works on new Unity versions (2019.4):

  private void OnDestroy()
         {
 #if UNITY_EDITOR
             if (!UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
             {
                 if (Time.frameCount != 0 && Time.renderedFrameCount != 0)//not loading scene
                 {
                     if (componentToDestroy != null)
                         DestroyImmediate(componentToDestroy);
                 }
             }
             else
 #endif
             {
                 if (componentToDestroy != null)
                     Destroy(componentToDestroy);
             }
         }

Comment
Add comment · Show 1 · 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 KingsHere · Jul 24, 2020 at 11:39 AM 0
Share

Exactly what I was searching for, Thanks!!

avatar image
0

Answer by sindrijo_ · Nov 28, 2016 at 11:11 AM

I little gotcha for Editor side: OnDestroy will only be called on an object that have had "OnAwake" called on them, meaning if you somehow spawn an object as a child on a disabled object that has your script or you add your script to a disabled object OnDestroy will not be called if you never activate the object.

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
avatar image
0

Answer by IgorAherne · Jan 25, 2017 at 06:46 PM

The following code can be placed directly into MonoBehavior will allow you to get a callback, even though object was "technically deleted". But, you are not allowed to use anything like this.gameObject or this.transform etc.

However, you could use this to "clean-up" any entries from your singletons, static classes or Scriptable objects who were pointing at this, etc (their references to it would now exist as 'null', meaning their Lists or Dictionaries might contain null entries).

 #if UNITY_EDITOR
    //tells if we have already hooked-up to the SceneView delegate, once, some time ago
     [System.NonSerialized] 
    bool linked_SV = false;


    public void OnDrawGizmos() {
         if(linked_SV == false) {
             linked_SV = true;
             SceneView.onSceneGUIDelegate -= OnSceneDraw;
             SceneView.onSceneGUIDelegate += OnSceneDraw;
         }
     }
 
 
     void OnSceneDraw(SceneView sceneView) {
 
         try {
             this.gameObject.name = this.gameObject.name;
         }
         catch{
             SceneView.onSceneGUIDelegate -= OnSceneDraw;
             // this gameObject was destroyed. 
              OnDestroy();
              SomeOtherFunction();
             return;
         }
  #endif


For example, I was using Graphics.DrawMesh, from within my OnSceneDraw(), and was successfully able to "unhook" my function from the SceneView.OnSceneViewDelegate, even after unity said it was deleted.

This was possible since unity "fakes the object's deletion", by substituting its own, special, "NULL-value". That's why after destroying any gameObject, it's also best to set the references to null, manually. Garbage collector will then remove it.

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
avatar image
0

Answer by Aloushi3 · Jul 24, 2020 at 11:44 AM

i don't know coding can you help by answering my post

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

15 People are following this question.

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

Related Questions

When I Multi-select gameobjects and press 'delete' 'OnDestroy' func is not called? 0 Answers

Need help reassigning variables after the deletion of an object has been undone. 0 Answers

I cant delete multiple instantiated prefabs 0 Answers

Detect when GameObject has been deleted / removed from scene 10 Answers

Update Graph after GameObject destruction 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