- Home /
For each (foreach) statement running hundreds of times.
I have a bit of code that respawns a character after death. It's still a work in progress, but is mostly functioning how I want. Instead of destroying the object I was hoping it would be more efficient to disable it and move it to a predefined point, then re-enable it. I have created a coroutine to handle this (the re-enabling part)which places all the gameobject's colliders and renderers into arrays then uses a foreach statement to re-enable them. There's a huge fps drop when this happens. I placed a debug.log line in the loop to see how often it was being called and it's anywhere from 50 - 500 times!
My understanding was that each instruction is executed once per item in the array (there are 8 renderers and 1 box collider). Renderers foreach is called 424 times (53 x 8 renderers) and colliders foreach is called 53 (53 x 1 box collider). Shouldn't it just run 8 times and 1 time?!
IEnumerator Recreate()
{
yield return new WaitForSeconds(1);
gameObject.transform.position = SpawnLoc;
Component[] renderers = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
Component[] colliders = gameObject.GetComponentsInChildren<BoxCollider>();
foreach(SkinnedMeshRenderer item in renderers)
{
item.enabled = true;
Debug.Log ("skinned mesh renderers being turned on");
Debug.Log ( renderers.Length);
}
health = maxHealth;
mana = maxMana;
GetComponent<LifeHUD>().justRespawned = true;
isAlive = true;
yield return new WaitForSeconds(3);
foreach(BoxCollider item in colliders)
{
item.enabled = true;
Debug.Log ("BoxColliders being turned on");
}
}
Answer by Eric5h5 · Mar 14, 2014 at 11:29 PM
You're calling the function repeatedly elsewhere, probably Update, so you have many instances running.
Oh, so much better! I was needlessly running this when a boolean was switched to false, then was setting it to true within the coroutine (after a waitforseconds). Dumb.
Thanks Eric, and a HUGE thanks for being an unknowing code tutor! You have answered so many questions on these "forums" that I've been stumped by and learned from!
Your answer
![](https://koobas.hobune.stream/wayback/20220613140249im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rendering an object multiple times 3 Answers
Problems with multiple layers. 1 Answer
Cloning Problem Script 0 Answers
Code executing multiple times? 1 Answer