在Unity中,如何在通过编辑器删除另一个组件的同时通过脚本删除一个组件?
In Unity, how to delete a component via script when deleting another component via the editor?
上下文:我正在编辑一个预制件,上面有两个组件,都是自定义脚本。
编辑预制件时,我想在编辑器中删除组件 Container Sync 的同时删除组件 Container Descriptor,方法是右键单击它并单击 Remove Component。见下图。
在 ContainerDescriptor 中,我引用了 ContainerSync 脚本。
public class ContainerDescriptor : MonoBehaviour
{
public ContainerSync containerSync;
}
我尝试使用 ContainerDescriptor 脚本的 OnDestroy() 方法,但是当以这种方式删除 ContainerDescriptor 时它没有被调用。
On this thread 如果您像您一样通过上下文菜单删除该组件,至少有一个解决方案。
使用 [ExecuteAlways]
通常只在播放模式中调用的事件消息调用也会在编辑和预制模式中调用!
你可以做一些事情,例如
[ExecuteAlways]
public class ContainerDescriptor : MonoBehaviour
{
public ContainerSync containerSync;
#if UNITY_EDITOR
private void OnDestroy ()
{
if(containerSync)
{
if(Application.isPlaying)
Destroy(containerSync);
else
DestroyImmediate (containerSync);
}
}
#endif
}
请注意,尽管专门针对预制件这可能仍然会失败,因为 afaik Destroy
和 DestroyImmediate
都不能在预制件内部使用(参见 here)
上下文:我正在编辑一个预制件,上面有两个组件,都是自定义脚本。
编辑预制件时,我想在编辑器中删除组件 Container Sync 的同时删除组件 Container Descriptor,方法是右键单击它并单击 Remove Component。见下图。
在 ContainerDescriptor 中,我引用了 ContainerSync 脚本。
public class ContainerDescriptor : MonoBehaviour
{
public ContainerSync containerSync;
}
我尝试使用 ContainerDescriptor 脚本的 OnDestroy() 方法,但是当以这种方式删除 ContainerDescriptor 时它没有被调用。
On this thread 如果您像您一样通过上下文菜单删除该组件,至少有一个解决方案。
使用 [ExecuteAlways]
通常只在播放模式中调用的事件消息调用也会在编辑和预制模式中调用!
你可以做一些事情,例如
[ExecuteAlways]
public class ContainerDescriptor : MonoBehaviour
{
public ContainerSync containerSync;
#if UNITY_EDITOR
private void OnDestroy ()
{
if(containerSync)
{
if(Application.isPlaying)
Destroy(containerSync);
else
DestroyImmediate (containerSync);
}
}
#endif
}
请注意,尽管专门针对预制件这可能仍然会失败,因为 afaik Destroy
和 DestroyImmediate
都不能在预制件内部使用(参见 here)