- Home /
Question by
$$anonymous$$ · Nov 15, 2014 at 03:37 AM ·
componentsmemory-leak
Infinite Loop while Removing Components
Why is this giving me an infinite loop? (It is crashing eclipse because System out of memory, so I am assuming it is an infinite loop anyways...)
while (transform.gameObject.GetComponent<MyComponent>() != null)
{
GameObject.Destroy(transform.gameObject.GetComponent<MyComponent>());
}
I also get the same error with:
while (transform.gameObject.GetComponents<MyComponent>().Length > 0)
{
GameObject.Destroy(transform.gameObject.GetComponent<MyComponent>());
}
Comment
Answer by zharik86 · Nov 15, 2014 at 07:21 AM
Yes, your script is freeze application or crush, because actual object destruction is always delayed until after the current Update loop, but will always be done before rendering. You put object in queue on deleting. You can use instead of Destroy() function DestroyImmediate(). But Unity are strongly recommended to use Destroy. Or use for 1 script simple:
GameObject.Destroy(transform.gameObject.GetComponent<MyComponent>()); //without while
For 2d script:
int i = transform.gameObject.GetComponents<MyComponent>().Length;
while (i > 0) {
GameObject.Destroy(transform.gameObject.GetComponent<MyComponent>());
i--;
}
But I would use loop"for":
for(int i = 0; i < transform.gameObject.GetComponents<MyComponent>().Length; i++) {
GameObject.Destroy((transform.gameObject.GetComponents<MyComponent>())[i]);
}
I hope this it will help you.