Suppose a game checks which enemies are close enough to attack. The count, loop index, and distance calculation are needed only while the check runs. Stack memory is suited to such short-lived function data: it is limited in size, follows a last-in, first-out model, and its space can be reclaimed when a function returns. section 2.2.1
Listing 2.2 A function to count enemies in a specific range
public int CountEnemiesInRange(
EnemyData enemyData,
Vector2 playerPosition,
float range,
int numEnemies)
{
int count = 0;
for (int i = 0; i < numEnemies; i++)
{
float distance = Vector2.Distance(enemyData.Position[i], playerPosition);
if (distance <= range)
{
count++;
}
}
return count;
}The enemy-range function makes the distinction concrete: its temporary working values belong to the call, while its enemy-data parameter is a reference to data held elsewhere. section 2.2.1
Think of each call as using a stack frame for its temporary data. A call made inside that function finishes before the outer call does, so their lifetimes fit the last-in, first-out pattern. This is a useful model, not a promise about physical placement: a compiler or runtime may keep values in registers, inline calls, or arrange frame contents differently. section 2.2.1
Before changing an allocation in a per-frame Unity path, distinguish the value from what it refers to:
- A local array variable may be part of a stack frame, but an ordinary C# array’s contents are allocated on the heap. Setting the variable to null does not immediately make that heap space reusable. section 3.2.1
- A small, temporary C# struct can be appropriate for values used together; passing a struct by value copies it. A struct stored inside a heap object is not thereby stored on the stack. section 2.7 section 2.8
- Keep genuinely temporary allocations short-lived where practical, but use the heap for long-lived game data and dynamically allocated arrays and strings. section 2.7 section 3.2.4
The payoff is simpler lifetime management and, for stack-resident data, contiguous storage that can help data locality. It is not a reason to move every game structure onto the stack: capacity and lifetime limit its use. Nor is an array used *like a stack* necessarily stack memory; an enemy-index array can implement last-in, first-out access while remaining an array. section 2.8 section 6.5.3
