Tại sao Performance Mobile quan trọng?
Mobile devices có giới hạn về CPU, GPU, RAM và battery. Việc tối ưu hóa performance không chỉ giúp game chạy mượt mà còn tiết kiệm pin và tương thích với nhiều thiết bị hơn.
1. Object Pooling
Thay vì liên tục tạo và hủy objects, hãy sử dụng object pooling:
public class ObjectPool : MonoBehaviour
{
public GameObject prefab;
private Queue<GameObject> pool = new Queue<GameObject>();
public GameObject GetObject()
{
if (pool.Count > 0)
return pool.Dequeue();
else
return Instantiate(prefab);
}
public void ReturnObject(GameObject obj)
{
obj.SetActive(false);
pool.Enqueue(obj);
}
}
2. Texture Optimization
- Sử dụng texture compression phù hợp (ASTC cho Android, PVRTC cho iOS)
- Giảm kích thước texture khi có thể
- Sử dụng mipmaps cho textures
- Tránh alpha channels không cần thiết
3. Audio Optimization
- Compress audio files
- Load audio on demand
- Use audio pooling for frequent sounds
4. Code Optimization
// Tránh allocations trong Update()
void Update()
{
// BAD: Tạo string mới mỗi frame
// someText.text = "Score: " + score.ToString();
// GOOD: Cache string
if (scoreChanged)
{
someText.text = "Score: " + score.ToString();
scoreChanged = false;
}
}
5. Profiling và Testing
Luôn sử dụng Unity Profiler để identify bottlenecks và test trên thiết bị thật.