- Home /
Is this generalized Destroy function safe to use?
I’ve been using dynamic meshes and custom scriptable objects in my program. Sometimes these objects are stored as ASSETS, on disk, sometimes they are just dynamically created and never stored to disk. Unfortunately, my classes that USE/reference these objects are unaware if they are a disk stored asset, or dynamically created. Oftentimes these objects are used while in editor mode, as opposed to just when the game is running. (In this case the dynamically created objects are stored inside a scene’s GameObject.)
I do the following whenever I reassign one of these object references in my code. First, I confirm the new Object is actually different from the currently assigned object. If so, to keep the replaced objects from “leaking” I call Objet.Destroy() on them, just before reassignment. Of course, this generates an error, when I’m in edit mode, that I’m supposed to use DestroyImmidiate(), which in turn leads to messages about destroying saved assets.
So I wrote the super generalized Destroy function, shown below, to try and handle the various conditions where different destroy functions need to be called (or not called!). I get the feeling I’m doing something dangerous here, and there is SOME reason I should not use the below. But, I can’t put my finger on it.
Is there some reason I do NOT want to use the below, or does it seem perfectly safe?
public static void DestroyObjectAppropriately(Object destroyme)
{
if (destroyme == null) return;
if (Application.isPlaying)
{
Object.Destroy(destroyme);
return;
}
else
{ //if app is not playing, safe to assume we are in the editor. Still, the below #if is needed to allow release builds to compile, or the use of AssetDatabase will generate an error.
#if UNITY_EDITOR
if (AssetDatabase.GetAssetPath(destroyme) == "") //saved assets will not have a black AssetPath
Object.DestroyImmediate(destroyme, false);
#endif
}
}
In my code, I would use this function like so:
if (objectFramedMeshFilter.sharedMesh != wireFrameSourceMeshAsset)
{
ResourceSystem.DestroyObjectAppropriately(wireFrameSourceMeshAsset);
wireFrameSourceMeshAsset = objectFramedMeshFilter.sharedMesh;
}
Looks pretty solid to me. You can use string.Empty on line 13 if you really want to be efficient - but other than that it should work fine!
Think I'll use this type of method myself, as I find myself getting annoyed with hard coding individual destroy methods :)