Advertisement
MariuszPoz

Displaying the value of a variable on the screen

Jan 8th, 2025 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.07 KB | Source Code | 0 0
  1. // https://unity-is-easy.blogspot.com
  2. // VISIT MY PAGE TO LEARN UNITY :)
  3. // This script was used in this tutorial:
  4. // https://unity-is-easy.blogspot.com/2025/01/displaying-value-of-variable-on-screen.html
  5.  
  6. using UnityEngine;
  7. using TMPro;
  8.  
  9. public class DisplayCameraCoords : MonoBehaviour
  10. {
  11.     public TextMeshProUGUI labelCoords; // Reference to the TextMeshPro object
  12.  
  13.     /*
  14.      
  15.         The mainCamera variable is used internally by the script to fetch the camera's position.
  16.         Since it doesn't need to be exposed to other scripts or the Unity Inspector, it can remain private.
  17.         Private variables are accessible only within the script they are declared in, making the code more encapsulated and reducing unintended interactions.
  18.    
  19.         Using Camera.main, the script automatically finds the Main Camera in the scene, so there’s no need for manual assignment in the Inspector.
  20.         This simplifies the workflow and reduces the risk of human error (e.g., forgetting to assign the camera in the Inspector).
  21.  
  22.     */
  23.  
  24.     private Camera mainCamera;
  25.  
  26.     void Start()
  27.     {
  28.         // Find the Main Camera
  29.         mainCamera = Camera.main; // bind our MAIN Camera object with "mainCamera" variable
  30.          
  31.         // Ensure the labelXcoords is assigned.
  32.         // Display error message if not
  33.  
  34.         if (labelCoords == null)
  35.         {
  36.             Debug.LogError("TextMeshPro X object is not assigned in the Inspector.");
  37.         }
  38.  
  39.     }
  40.  
  41.     void Update()
  42.     {
  43.        
  44.         // if camera is bound and labelCoords is bound too then:
  45.        
  46.         if (mainCamera != null && labelCoords != null)
  47.         {
  48.             // Get the X, Y, Z position of the Main Camera
  49.             float cameraX = mainCamera.transform.position.x;
  50.             float cameraY = mainCamera.transform.position.y;
  51.             float cameraZ = mainCamera.transform.position.z;
  52.  
  53.             // Display it in the TextMeshPro label
  54.             labelCoords.text = $"{cameraX:F2} / {cameraY:F2} / {cameraZ:F2}"; // "F2" limits to 2 decimal places
  55.         }
  56.     }
  57. }
  58.  
Tags: C# Unity
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement