- Home /
Detect when a component has been removed.
I have a component that generates a .asset file when it is attached. If it is removed, then the .asset file must also be deleted otherwise it will become an orphan.
I tried using OnDestroy(), but when switching from play mode or edit mode, OnDestroy() gets called on any component in the scene. I'm guessing Unity is serializing the edit mode objects so that when it exits play mode, it can revert back to the original object's field values, but it has to delete the scene objects during the switch.
Maybe I should be managing my asset files in a different way?
I don't know why are you generating .asset on the fly, but...
After some research, I've done some testing and found out that OnApplicationQuit() is called before OnDestroy() ("But in the Unity $$anonymous$$anual is different!!" well, don't blame me).
So, you could use something like that:
bool isQuiting;
void OnApplicationQuit()
{
isQuiting = true;
}
void OnDestroy()
{
if (isQuiting)
{
return;
}
// Destroy stuff
}
Thanks. I'm generating .assets because my component needs access to some data structure that is usually unchanging but might sometimes change. I want it to survive between loads and unloads, so I'm storing it in a .asset. Writing to .asset only happens when the user saves the scene or project.
I see, but why not go with DontDestroyOnLoad to persist between scenes and serialization to survive on loads and unloads? I am new to Unity, but I never saw that way of managing data until now.
Answer by Croolsby · Jan 07, 2016 at 10:38 AM
Using Application.isPlaying
and Application.isEditor
is not sufficient because removing a component and switching from edit mode to play mode both make isPlaying == false && isEditor == false
.
The solution is to use EditorApplication.isPlayingOrWillChangePlaymode
. Then you know a component is being removed (or GO destroyed) by the user in edit mode if isEditor && !isPlaying && !isPlayingOrWillChangePlaymode
.
Your answer
Follow this Question
Related Questions
Only PreProcess assets on first import. 1 Answer
Is there a way to build Addressable Assets outside of the Editor? 0 Answers
Instantiate, problem on transform position 1 Answer
When looping through assetbundle assetdatabase how do you reference a material object 0 Answers
Proper way to refresh asset 0 Answers