如何在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();
}
}
几乎没有什么问题。首先,如果销毁对象,则会丢失"木材计数"字段,因为它将随对象一起销毁。第二,如果对象被破坏,Update方法永远不会执行,因此文本不会更新。
解决方案1:解决此问题的更快方法是使woodCount为静态。然后更新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);
}
}
}
解决方案1:如果你将游戏逻辑与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应该是一个整数
尝试交换的这两行
woodCount = woodCount + 1;
Destroy(gameObject);
private void OnTriggerEnter2D(Collider2D other){
if (other.CompareTag("sword")){
woodCount = woodCount + 1;
woodText.text = woodCount.ToString();
Destroy(gameObject);
}
}