Friday, May 17, 2024
HomeGame Developmentc# - Unity: Cannot access TMP_Text object from script in gameobject

c# – Unity: Cannot access TMP_Text object from script in gameobject


I’m trying to set the color property of a TMP_Text object but keep getting Object reference not set to instance of an object error. Setup is as follows;

  1. I have a Canvas (game hud) that has 6 TMP_Text objects in it for stats. 3 are static text and 3 are to be updated from other scripts.

  2. I have a gameobject that will be moving and a script that will change the text color of one of the values in the hud based on the game object velocity exceeding a fixed limit.

    using System.Collections.Generic;
    using UnityEngine;
    using TMPro;
    
    public class shipCollision : MonoBehaviour {
      // The TMP_Text object is dragged into the inspector before runtime
      public TMP_Text txtVertVelVal;
    
       private void Update() {
         landerRb = lander.GetComponent<Rigidbody>();
    
         Vector3 landerVelocity = landerRb.velocity;
         if(landerVelocity.y > 3f) {
           txtVertVelVal.color = Color.red;
         } else {
           txtVertVelVal.color = Color.green;
         }
    }
    
    

So, is this failing to because I am not referencing the parent Canvas maybe?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments