I'm having difficulty changing text, on unity3d using TextmeshPro.

I'm new to coding and Unity, so I really don't know what to do.

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

It's supposed to change the text that organTruth and Score display, the soldAmount should be displayed after increasing by 1, and the organTruth should be a 1 after a collision.

1 Answers

0
Community On

You have set your OnTriggerEnter inside the update loop. You have to place it outside your update function. That should fix the problem.