- Home /
Question by
mthicke2 · Nov 26, 2014 at 06:13 AM ·
destroycomponentinteractive cloth
Component not destroyed
I am destriying the InteractiveCloth component of a GameObject and then adding it again but Unity gives an error "Can't add component 'InteractiveCloth' to Cloth because such a component is already added to the game object!" even though the InteractiveCloth component has been destroyed and no longer shows up in the inspector when the error pauses the game.
my code: Destroy(GetComponent()); Destroy(GetComponent());
InteractiveCloth cloth = gameObject.AddComponent("InteractiveCloth") as InteractiveCloth;
cloth.mesh = transform.GetComponent<MeshFilter>().mesh;
ClothRenderer cr = gameObject.AddComponent("ClothRenderer") as ClothRenderer;
cloth.AttachToCollider(player.transform.collider, true, true);
cloth.AttachToCollider(target.transform.collider, true, true);
Comment
Best Answer
Answer by fafase · Nov 26, 2014 at 07:03 AM
Destroy actually happens at the end of the frame, so I think when you try to add it it is actually still there and then destroy.
Solution would be to use DestroyImmediate but it is not recommended for some reasons. Other way could be to use a coroutine:
private IEnumerator RemoveAddComponent(Component component)
{
Destroy(component);
yield return null; // Quit and back here next frame
AddComponent(component);
}
I'd guess that should work.
Your answer
![](https://koobas.hobune.stream/wayback/20220613172440im_/https://answers.unity.com/themes/thub/images/avi.jpg)