Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://unity-is-easy.blogspot.com
- // VISIT MY PAGE TO LEARN UNITY :)
- // This script was used in this tutorial:
- // https://unity-is-easy.blogspot.com/2025/01/displaying-value-of-variable-on-screen.html
- using UnityEngine;
- using TMPro;
- public class DisplayCameraCoords : MonoBehaviour
- {
- public TextMeshProUGUI labelCoords; // Reference to the TextMeshPro object
- /*
- The mainCamera variable is used internally by the script to fetch the camera's position.
- Since it doesn't need to be exposed to other scripts or the Unity Inspector, it can remain private.
- Private variables are accessible only within the script they are declared in, making the code more encapsulated and reducing unintended interactions.
- Using Camera.main, the script automatically finds the Main Camera in the scene, so there’s no need for manual assignment in the Inspector.
- This simplifies the workflow and reduces the risk of human error (e.g., forgetting to assign the camera in the Inspector).
- */
- private Camera mainCamera;
- void Start()
- {
- // Find the Main Camera
- mainCamera = Camera.main; // bind our MAIN Camera object with "mainCamera" variable
- // Ensure the labelXcoords is assigned.
- // Display error message if not
- if (labelCoords == null)
- {
- Debug.LogError("TextMeshPro X object is not assigned in the Inspector.");
- }
- }
- void Update()
- {
- // if camera is bound and labelCoords is bound too then:
- if (mainCamera != null && labelCoords != null)
- {
- // Get the X, Y, Z position of the Main Camera
- float cameraX = mainCamera.transform.position.x;
- float cameraY = mainCamera.transform.position.y;
- float cameraZ = mainCamera.transform.position.z;
- // Display it in the TextMeshPro label
- labelCoords.text = $"{cameraX:F2} / {cameraY:F2} / {cameraZ:F2}"; // "F2" limits to 2 decimal places
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement