unity UI 元素始终面向主相机

122 阅读1分钟

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtMainCamera : MonoBehaviour
{
    
    private Transform _mainCameraTransform;

    private void Start()
    {
        if (Camera.main != null) _mainCameraTransform = Camera.main.transform;
    }
    
    private void LateUpdate()
    {
        // 让UI始终面向主相机
        var rotation = _mainCameraTransform.rotation;
        
        // rotation * Vector3.forward 主相机前方的向量
        // rotation * Vector3.up 主相机上方的向量
        
        transform.LookAt(transform.position + rotation * Vector3.forward, 
            rotation * Vector3.up);
    }
}

image.png

更新函数放在 lateUpdate 的目的有两个

  1. 位置更新完成: lateUpdate 是在每一帧更新之后调用,包括所有的Update 方法执行完成。可以确保UI 朝向调整时,发生在被其他脚本或者系统修改后。
  2. 避免闪烁: 如果放在Update 函数中处理,可能会导致UI 朝向的修正在Camera 移动的过程中发生,从而导致UI 的抖动或者闪烁的现象。lateUpdate 可以确保是在Camera 位置更新之后发生。