如何使用预制件更改文本?

How do I change text with a prefab?

如何在 C# 脚本中创建和更改文本?

我目前有这段代码,但它不起作用,因为我告诉脚本我要更改的文本是什么:

 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();
    }
}

尝试交换这两行

woodCount = woodCount + 1;
Destroy(gameObject);


private void OnTriggerEnter2D(Collider2D other){
        if (other.CompareTag("sword")){
          woodCount = woodCount + 1;
          woodText.text = woodCount.ToString();
          Destroy(gameObject);
        }   
}

问题不大。首先,如果您销毁对象,您将丢失 woodCount 字段,因为它将与对象一起销毁。其次,如果对象被销毁,则 Update 方法永远不会执行,因此文本不会更新。

解决方案一: 解决这个问题的更快方法是创建 woodCount static。然后更新 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);
        }
    }
}

解决方案一: 更好的方法是将游戏逻辑与 UI... 分开,例如:

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 应该是一个整数,如果你只增加一个