V
V
Vqrlamov2021-07-13 16:20:58
Unity
Vqrlamov, 2021-07-13 16:20:58

How to find UI Text by tag and use the text in the script itself?

I'm trying to find the text by the tag in the script and change the number of coins when picking, but I'm doing something wrong, I can't figure out what exactly. Unity itself produces a zero error in Update

The script is attached to the text itself, here is the script itself:

using UnityEngine;
using UnityEngine.UI;

public class CoinsScript : MonoBehaviour
{
Text CountOfCoins;
public static int coinsCounter;

void Start()
{
CountOfCoins = GameObject.Find("CountCoin").GetComponent();
coinsCounter = 0;
}

void Update()
{
CountOfCoins.text = "Coins: " + coinsCounter;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
B1tH0ven, 2021-07-13
@B1tH0ven


When using GetComponent , indicate the type of the component (GetComponent"less sign"Text"greater sign"();) is
suitable here
. ) there is no Text component.
Might be useful: Any search, by name, tag or type, is a very costly process, try to serialize the text field:
[Serialize Field] private Text CountOfCoins;
Or
public Text CountOfCoins;
After that, drag the desired specific object with text from the Hierarchy window to the slot on the script in the Inspector window.
An additional bonus - there will be no problems, as with tags, if you make two objects with the "CountCoin" tag. The text for coins will always be exactly the text that you specify in the script field.

I
i__egor, 2021-07-14
@i__egor

You have a search by the name of the object, if by tags then GameObject.FindGameObjectWithTag("CountCoin"). but in general it is better to search by name and set a specific path, you know where this text is located in the hierarchy. e.g. "Canvas/Panel/TxtCoin"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question