Tối ưu bằng Caching Components
C# Code
using UnityEngine;
public class CachingExample : MonoBehaviour
{
// --- CÁCH LÀM CHƯA TỐI ƯU ---
/*
void Update()
{
// GetComponent() được gọi mỗi frame, rất tốn kém hiệu năng.
Rigidbody rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.up * 10f);
}
*/
// --- CÁCH LÀM ĐÃ TỐI ƯU (CACHING) ---
private Rigidbody cachedRigidbody;
private Transform cachedTransform;
private AudioSource cachedAudioSource;
void Awake()
{
// Tìm và lưu lại tham chiếu đến các component một lần duy nhất.
cachedRigidbody = GetComponent<Rigidbody>();
cachedTransform = transform; // 'transform' là một trường hợp đặc biệt, nó cũng là một lời gọi GetComponent ngầm.
cachedAudioSource = GetComponent<AudioSource>();
}
void Update()
{
// Sử dụng tham chiếu đã được cache, nhanh hơn rất nhiều.
if (cachedRigidbody != null)
{
cachedRigidbody.AddForce(Vector3.up * 10f);
}
// Di chuyển đối tượng bằng transform đã cache.
cachedTransform.position += Vector3.forward * Time.deltaTime;
}
public void PlaySound(AudioClip clip)
{
if(cachedAudioSource != null)
{
cachedAudioSource.PlayOneShot(clip);
}
}
}Một kỹ thuật tối ưu cơ bản và quan trọng: cache (lưu trữ) các tham chiếu đến component trong Awake() hoặc Start() để tránh gọi GetComponent() liên tục trong Update(), giúp giảm đáng kể chi phí hiệu năng.