Search Unity

Resolved Run-time error when changing string in TextMeshPro.

Discussion in 'Scripting' started by unitsume, Nov 18, 2022.

  1. unitsume

    unitsume

    Joined:
    Oct 7, 2022
    Posts:
    31
    Hello.
    A runtime error occurred when rewriting the TextMeshPro string.
    The string has changed.
    Why is this code giving an error?

    error message
    NullReferenceException: Object reference not set to an instance of an object
    BoardTateyaController.Update () (at Assets/Scripts/BoardTateyaController.cs:32)


    BoardTateyaController.cs
    Code (csharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5.  
    6. public class BoardTateyaController : MonoBehaviour
    7. {
    8.     public TMP_Text myText;
    9.     public int cnt = 0;
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         string txt = "Hello";
    20.  
    21.         if (cnt % 2 == 1)
    22.         {
    23.  
    24.             txt = "Hello";
    25.         }
    26.         else
    27.         {
    28.             txt = "World";
    29.  
    30.         }
    31.  
    32.         myText.SetText(txt); // error occurred here
    33.  
    34.         cnt++;
    35.     }
    36.  
    37. }
    my execution environment
    Unity Editor 2021.3.11f1
    TextMeshPro 3.0.6

    my settings
    [Hierarchy] > [+] > [3D Object] > [Text-TextMeshPro]
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    Debug.Log(myText)
    will tell you the reason.
     
    unitsume likes this.
  3. unitsume

    unitsume

    Joined:
    Oct 7, 2022
    Posts:
    31
    Thank you.
    I've confirmed.
    it is null.
    I made a mistake in the inspector settings.
     
    RadRedPanda likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    For future reference, you NEVER need to post in the forums for a NullReferenceException.

    Why? Because it will not solve your problem. These three steps will ALWAYS solve your problem:

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that
     
    unitsume likes this.
  5. unitsume

    unitsume

    Joined:
    Oct 7, 2022
    Posts:
    31
    Thank you.
    I learned a lot!