Add value to Text

Hey, i’m quite new to Unity and currently have the following problem:
i want to add a value (1) to my Text everytime a gameObject gets destroyed, so i tried the following code with int but they cause heavy bugs in the game (my gameObjects stop shrinking). So i wanted to ask is there another way to add values to my text?
NOTE : check if gameobject = null won’t work beacuse they spawn every few seconds so there are always atleast 2 in the scene

  • using System.Collections;

  • using System.Collections.Generic;

  • using UnityEngine;

  • using UnityEngine.UI;

    • public class Hexagon : MonoBehaviour
  • {

    • public Rigidbody2D rb;
  • public int currentScore;

  • public float shrinkSpeed = 1.5f;

  • public Text Score;

    • // Start is called before the first frame update
  • void Start()

  • {

  • rb.rotation = Random.Range(0f, 360f);

  • rb.transform.localScale = Vector3.one * 10f;

    • Score.text = “1”;
  • }

    • // Update is called once per frame
  • void Update()

  • {

  • //Score.text = “” + currentScore; <= this one

    • rb.transform.localScale -= Vector3.one * shrinkSpeed * Time.deltaTime;
    • if (transform.localScale.x <= .05f)
  • {

  • Destroy(gameObject);

  • //currentScore = currentScore + 1; <= and this one

  • }

  • }

  • }

Strange thing is the Score.text = “1”; in Start works

Use code tags to post code. See the sticky post on the forum.

It looks like each object that is getting destroyed is tracking its own copy of the score. You need to use a centralized object (maybe one attached to the same GameObject as your score text, for simplicity). Move currentScore to that object, and update the score there instead of on individual objects.

1 Like