Search Unity

Question Counter Text Mesh is not updating after destroying the first Object

Discussion in 'Getting Started' started by ZockerSofa, Nov 15, 2021.

  1. ZockerSofa

    ZockerSofa

    Joined:
    Nov 8, 2021
    Posts:
    3
    I am trying to make a 2D Game where you can collect cherrys and everytime you do, it is supposed to be destroyed and a counter should be displayed. I tried to debug with the prints and that is working too. So I dont know why the counter in the TextMesh isnt being updated when I pick up the second, third, ... cherry.

    Code (CSharp):
    1. using System;
    2. using TMPro;
    3. using UnityEngine;
    4.  
    5. public class CherryCollected : MonoBehaviour
    6. {
    7.     public Animator animatorCherry;
    8.    
    9.     public TextMeshProUGUI textCherry;
    10.     private int _cherry = 0;
    11.  
    12.     private void OnTriggerEnter2D(Collider2D other)
    13.     {
    14.         if (other.gameObject.CompareTag("Player"))
    15.         {
    16.             PlayAnimationAndDestroyCherry();
    17.             _cherry++;
    18.             print("count++");
    19.             textCherry.text = _cherry.ToString();
    20.             print("canvas number");
    21.         }
    22.     }
    23.  
    24.     private void PlayAnimationAndDestroyCherry()
    25.     {
    26.         Destroy(gameObject, .3f);
    27.         animatorCherry.Play("Item_Feedback");
    28.     }
    29. }
     
  2. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    Use this

    print("Cherry count = " + _cherry.ToString());
     
  3. ZockerSofa

    ZockerSofa

    Joined:
    Nov 8, 2021
    Posts:
    3
    For some reason it is not counting up. I am guessing it has to do something with that I am using just copies of the object. Before I had prefabs of it but I changed it bc I had problems with playing the animaton of collecting the cherry for each individual cherry
     
  4. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    I've been using Unity for 9 years now and this is the first I've seen Destroy called with a second parameter. I had no idea you could destroy after a delay!

    I'm wondering if it's possible that calling Destroy on the object is also stopping the execution flow of the script inside this component. Can you try rearranging your code so that the Destroy only gets called after you do all the incrementing and text updating?