我正在尝试在Unity上使用TextMeshPro显示文本,使代码运行,没有错误

时间:2019-04-29 05:46:05

标签: c# unity3d

使用TextmeshPro在unity3d上更改文本时遇到困难。

我是编码和Unity的新手,所以我真的不知道该怎么做。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class PlayerController : MonoBehaviour
{
    public float speed = 1.0f;
    private int soldAmount;
    private int currentAmount;
    Rigidbody2D rigidbody2d;
    TextMeshProUGUI graveValue;
    TextMeshProUGUI scoreValue;

    // Start is called before the first frame update
    void Start()
    {
        scoreValue = GameObject.Find("Score").GetComponent<TextMeshProUGUI>();
        graveValue = GameObject.Find("OrganTruth").GetComponent<TextMeshProUGUI>();
        rigidbody2d = GetComponent<Rigidbody2D>();
        currentAmount = 0;
        soldAmount = 0;
    }

    // Update is called once per frame
    void Update()
    {
        float Horizontal = Input.GetAxis("Horizontal");
        float Vertical = Input.GetAxis("Vertical");
        Vector2 position = rigidbody2d.position;
        position.x = position.x + speed * Horizontal;
        position.y = position.y + speed * Vertical;
        rigidbody2d.position = position;

        void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.gameObject.tag == "Graveyard")
            {
                while(currentAmount < 1)
                {
                    currentAmount = currentAmount + 1;
                    graveValue.SetText(currentAmount.ToString());
                }
            }

            if(collision.gameObject.tag == "OrganBuyer")
            {
                while(currentAmount == 1)
                {
                    soldAmount = soldAmount + 1;
                    scoreValue.SetText(soldAmount.ToString());
                }
            }
        }
    }
}

应该更改organTruth和Score显示的文本,将soldAmount增加1后再显示sellAmount,并且碰撞后organizeTruth应该为1。

1 个答案:

答案 0 :(得分:0)

您已在更新循环中设置了OnTriggerEnter。您必须将其放置在更新功能之外。那应该可以解决问题。