foreach (Transform child in gameobject.transform)
{
spawnPoints.Add(child.position);
}
I need to convert this to optimize the performance as I’ve read somewhere that foreach loop produces 24bytes garbage/loop while for loop has better performance than this. but i couldnt get the gameobject.transform.
Just noting that in Unity 5.5, this memory leak from foreach loops has been fixed thanks to an upgraded compiler. If you’re using Unity 5.5 you don’t have to worry about it.
The compiler resolves the issue if the enumerator uncovered by the type being enumerated uncovers its enumerator as a ‘struct’.
Unfortunately, Transform does not, so it still creates garbage. (confirmed in version 5.5.0f3, the only way unity could get around this is if they had a special compiler that converted transform foreach loops to a for(childCount), which would require a rewrite of the compiler. And as far as I know, they’re just using the newer mono compiler)
It will resolves enumerators like List or Stack since they do uncover their enumerators as structs.
As for OP’s question…
FIRST OFF…
use code tags:
Second off. The methods you want are:
childCount
GetChild
Giving you:
for(int i = 0; i < this.transform.childCount; i++)
{
Transform child = this.transform.GetChild(i);
spawnPoints.Add(child.position);
}
I also removed the ‘gameObject’ parts, as I assume you’re attempting to access the local gameObject (that’s that fields name)… and you also have a local transform accessor as well, so why not just use that?