- Home /
Destroying an object in editor from inspector
I've created a custom editor for showing & editing lists base on the catlike coding tutorial. At the moment I can remove an object from my list which removes the reference to that object but I would really like it to also destroy the gameobject at the same time. Is there any straightforward way to do this?
The code for how buttons are currently handled is
private static void ShowButtons(SerializedProperty list, int index)
{
if(GUILayout.Button(moveButtonContentUp, EditorStyles.miniButtonLeft, miniButtonWidth))
{
if(index > 0)
{
list.MoveArrayElement(index, index - 1);
}
}
if (GUILayout.Button(moveButtonContentDown, EditorStyles.miniButtonMid, miniButtonWidth))
{
list.MoveArrayElement(index, index + 1);
}
if (GUILayout.Button(deleteButtonContent, EditorStyles.miniButtonRight, miniButtonWidth))
{
int oldSize = list.arraySize;
list.DeleteArrayElementAtIndex(index);
if (list.arraySize == oldSize)
{
list.DeleteArrayElementAtIndex(index);
}
}
}
Thanks in advance for any help!
Answer by DiegoSLTS · Apr 19, 2019 at 03:28 PM
Before DeleteArrayElementAtIndex you can get that element (GetArrayElementAtIndex) which returns a SerializedProperty, then call objectReferenceValue on that property which returns the object, then call Object.Destroy or Object.DestroyImmediate passing that object.
Hmm I tried this but I get nothing happening when I use DestroyImmediate, while using Destroy throws an error saying to use DestroyImmediate.
Wait no, it worked perfectly! I just needed to change the object reference I was destroying to a GameObject ins$$anonymous$$d of another script type and then it worked as it should. Thank you for your help!