Summary - Memory
- Game Development course
- Expert
- Lesson 12/47
- 4 min
Reinforce memory management with a summary task.
Memory management summary
Memory management is built on three habits: avoiding needless allocations, reusing objects and choosing the right type. The GC cleans up automatically but every allocation adds to its work. Pools, using structs and loading in parts all relieve memory.
int yeniNesne = 2;
int yenidenKullanilan = 5;When these habits are applied together, memory problems decrease.
Practice Memory summary task
In a class named BellekOzet, define a string field named yontem with the value "Pooling", an integer field named kazanc with the value 5, and an integer field named kare. In the Awake method set yontem to "Struct". In the Start method print the pieces "Yontem: ", yontem, " Kazanc: " and kazanc joined together with Debug.Log. In the Update method increase the kare counter by one every frame.
Starter code
using UnityEngine;
public class BellekOzet : MonoBehaviour
{
// yontem adli metin alanini "Pooling", kazanc adli tam sayi alanini 5 degeriyle tanimla
// kare adli tam sayi alanini tanimla
void Awake()
{
// yontem degerini "Struct" yap
}
void Start()
{
// "Yontem: " + yontem + " Kazanc: " + kazanc biciminde yazdir
}
void Update()
{
// kare sayacini her karede bir artir
}
}Sample solution
using UnityEngine;
public class BellekOzet : MonoBehaviour
{
string yontem = "Pooling";
int kazanc = 5;
int kare;
void Awake()
{
yontem = "Struct";
}
void Start()
{
Debug.Log("Yontem: " + yontem + " Kazanc: " + kazanc);
}
void Update()
{
kare++;
}
}Expected output
Yontem: Struct Kazanc: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following increases memory allocation?
void Update()
{
Nesne gecici = new Nesne();
}- Dropping references of unused objects
- Creating a new object with new every frame in Update Correct answer
- Taking objects from a pool
- Using structs for small data
Explanation: Producing an object with new every frame allocates constantly; pooling, structs and dropping references reduce allocation.
2 Write the array allocation
GameObject[] kasaDizisi = new ____[5];
GameObject[] kasaDizisi = new GameObject[5];
Explanation: In an array allocation the type name is repeated; for a GameObject array you use new GameObject[5].
3 Memory summary table
| Term | Meaning |
|---|---|
GC |
Cleans up unused objects |
Heap tahsisi |
Reserving memory with new |
struct |
Stored as a value type |
Object pooling |
The technique of reusing objects |