Skip to content

Instantly share code, notes, and snippets.

@Aaron8052
Last active January 5, 2024 02:24
Show Gist options
  • Save Aaron8052/2e1ea7f8c02c8c47e6c40d6f862570bd to your computer and use it in GitHub Desktop.
Save Aaron8052/2e1ea7f8c02c8c47e6c40d6f862570bd to your computer and use it in GitHub Desktop.
Unity游戏优化(三)对象缓存

Unity游戏优化(三)对象缓存

对于需要多次引用的对象,例如Transform,或其他对象,建议将其缓存到一个变量中以供后续使用,以减少不必要的开销。

using UnityEngine;
public class TestComponent : MonoBehaviour
{
private Transform _transform; //用于保存该物体transform的变量
private Camera _camera; //用于保存该物体Camera的变量
void Awake()
{
_transform = transform;//在组件初始化时获取该物体的transform组件并赋值到变量中
_camera = GetComponent<Camera>();//Camera同理
}
void MyFunction()
{
var position = _transform.position;//调用_transform变量,而不是transform
//...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment