how do I make and change text inside a c# script?
I have this code currently but it does not work because I tell the script what the text I want to change is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class treeBreak : MonoBehaviour
{
public float woodCount = 0;
public Text woodText;
private void OnTriggerEnter2D(Collider2D other){
if (other.CompareTag("sword")){
Destroy(gameObject);
woodCount = woodCount + 1;
}
}
void Update(){
woodText.text = woodCount.ToString();
}
}
There are few problems. First if you destroy the object you lose the woodCount field because it will be destroyed with the object. Second if the object is destroyed the Update method never execute so the text wont update.
Solution 1: The faster way to fix this is you make the woodCount static. And you update the text in the OnTriggerEnter2D.
public class treeBreak : MonoBehaviour
{
public static float woodCount = 0; // Stick with the class.
public Text woodText;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("sword"))
{
woodCount = woodCount + 1;
woodText.text = woodCount.ToString();
Destroy(gameObject);
}
}
}
Solution 1: The better way if you separate the game logic from the UI... for example:
public class TreeBreak : MonoBehaviour
{
public WoodCounter woodCounter;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("sword"))
{
woodCounter.Collect();
Destroy(gameObject);
}
}
}
public class WoodCounter : MonoBehaviour
{
public Text woodText;
private int woodCount = 0;
public void Collect()
{
woodCount++;
woodText.text = woodCount.ToString();
}
}
PS: woodCount should be an integer if you only increase by one