<aside> 📄 This script enables a UI canvas to follow the main camera. First create a UI canvas to the “World Space”, add an image component, attach the script to the image gameobject.
</aside>
using UnityEngine;
using UnityEngine.UI;
public class FollowCamera : MonoBehaviour
{
public Camera mainCamera; // Reference to the main camera
public RectTransform imageTransform; // Reference to the RectTransform of the image
void Start()
{
if (mainCamera == null)
{
mainCamera = Camera.main;
}
if (imageTransform == null)
{
imageTransform = GetComponent<RectTransform>();
}
}
void Update()
{
// Update the position of the image to follow the camera
Vector3 cameraPosition = mainCamera.transform.position;
imageTransform.position = new Vector3(cameraPosition.x, cameraPosition.y, imageTransform.position.z);
}
}