Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Object property works in Start, null in Update

Discussion in 'Scripting' started by ABCodeworld, Oct 11, 2020.

  1. ABCodeworld

    ABCodeworld

    Joined:
    Oct 11, 2020
    Posts:
    5
    Hi all. I have a bewildering problem involving what seems like basic script functionality. I have a new project using the Mobile 2D template in Unity 2020.8.1. I've done very little... simply added a Canvas, and a Text on the Canvas. Attached the following script to the Canvas. I get a NullReferenceException in the line in Update which attempts to print the Text's text property to the debug log. But the same line works in Start. Notice the object is a class variable, and is not null since "A" is being printed. It's like the text property is null in Update but not in Start. Any thoughts?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class CanvasMenu : MonoBehaviour
    7. {
    8.     Text txtTmp_c;
    9.  
    10.     void Start()
    11.     {
    12.         GameObject go = GameObject.Find("TmpText");
    13.  
    14.         if (go != null)
    15.         {
    16.             txtTmp_c = go.GetComponent(typeof(Text)) as Text;
    17.             UnityEngine.Debug.Log(txtTmp_c.text); // works fine, prints "New Text"
    18.         }
    19.    }
    20.  
    21.     void Update()
    22.     {
    23.         if (txtTmp_c = null)
    24.             return;
    25.  
    26.         UnityEngine.Debug.Log("A");
    27.         UnityEngine.Debug.Log(txtTmp_c.text); // exception here
    28.     }
    29. }
    30.  
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    You are setting it null in update.

    = is an assignment
    == is a comparison

    So change it to if( txtTmp_c == null)
     
    ABCodeworld and PraetorBlue like this.
  3. ABCodeworld

    ABCodeworld

    Joined:
    Oct 11, 2020
    Posts:
    5
    Wow! That slipped past me no matter how many times I read it. Thanks a bunch!