- Home /
Coroutine Array, set to null or initialize new array
So I have a jagged array of coroutines which I'm using to handle some simple, linear animations in my game. Now this isn't really a problem, but more of a concern for when I begin expanding the array to contain more stuff. So here's the question: When I load a new scene(level), I need to set all the coroutines within the jagged array to null.
Should I do this by just reinitializing the array like:
jagArrayOfCoroutines = new Coroutine[35][];
for(int i = 0; i < 35; i++){
jagArrayOfCoroutines[i] = new Coroutine[someOtherCount];
}
If I'm not mistakened, this would have the desired effect of every coroutine within the jagArrayOfCoroutines would be null. But would this create a bunch of garbage for Unity to have to clean up later, because we're completely neglecting the previous data which was stored within jagArrayOfCoroutines, but I'm assuming Unity's garbage collection would handle that(I'm not too familiar with how Unity's garbage collection works).
Or would this be the better approach:
for(int a = 0; a < jagArrayOfCoroutines.Length; a++){
for(int b = 0; b < jagArrayOfCoroutines[a].Length; b++){
jagArrayofCoroutines[a][b] = null;
}
}
Where you quite literally just iterate over every object within the array and set it to null. I'm assuming this might begin to have some overhead later on when I expand this to have a few hundred coroutines.
Answer by Pangamini · Nov 08, 2021 at 01:17 PM
Although things got better with Unity's incremental GC, I am still not a big fan of generating garbage, having experienced some really bad spikes from it. I try to avoid allocations whenever feasible. Anyway, in your case you are doing this only when loading a new level, which means it happens really infrequently, and also that there's a LOT more garbage produced elsewhere in that frame. So just don't worry about it, make your code readable and optimize later, if needed
I tried running each snippet of code in my game with thousands of croutons and neither had any real struggle or spike in performance(or at least it was hidden behind the rest of the level loading in). So I guess I was overthinking it. I appreciate the quick answer. Thank you