我到处都看到使用Camera.main
是一种不好的做法,我们不应该使用它。那么获取主相机对象的好方法是什么?
您应该在每个相机的生命周期中存储一次对该相机的引用,然后在其余代码中使用该存储的引用。例如:
// Reference initialization
public Camera mainCamera;
// Game code, executed once per frame or more
void Update()
{
Vector3 pos = mainCamera.transform.position;
}
Run Code Online (Sandbox Code Playgroud)
Camera.main
基本上与使用相同FindGameObjectsWithTag("MainCamera")
,因此相当昂贵。
场景中的主相机。
null
如果场景中没有这样的相机则返回。该属性FindGameObjectsWithTag
在内部使用并且不缓存结果。如果每帧多次使用,建议缓存返回值。Camera.main
DO N'T USE IT实际上是指每帧都使用一次。
如果只使用一次,也没有什么不好:
// Best is always if you can reference things already via the Inspector
[SerializeField] private Camera _camera;
private void Awake()
{
// As a FALLBACK get it ONCE e.g. in prefabs where you can't reference
// the scene camera
if(!_camera) _camera = Camera.main;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1606 次 |
最近记录: |