Home > OS >  I'm having trouble with changing the UI text when colliding with a player
I'm having trouble with changing the UI text when colliding with a player

Time:12-09

Here is the code:

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

public class PointSystem : MonoBehaviour
{
    public Rigidbody2D rb1;
    public Rigidbody2D rb2;
    public TextMeshProUGUI plr1T;
    public TextMeshProUGUI plr2T;
    public float UIVal1 = 1f;

    void Start()
    {
        plr1T = FindObjectOfType<TextMeshProUGUI>();
        plr2T = FindObjectOfType<TextMeshProUGUI>();
    }
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "PlayerAI")
        {
            UpdateUI();
        }  
    }

    void UpdateUI()
    {
        plr1T.text = (UIVal1.ToString());
        UpdateFloat();
    }
    
    void UpdateFloat()
    {
        UIVal1 =  1f;
    }

}

I want to change the UI text once they collide with an object and increase the value so if they hit it again the number in the text increases. It also does not show any errors. Please help.

I have tried using the ToString() method but it still does not change the text.

CodePudding user response:

I see few minor errors from your code:

  1. FindObjectOfType returns the first active loaded object that matches the specified type. It returns null if no Object matches the type. Since you have your plr1T and plr2T set in public, you can just assign them in the inspector. If you do that, you can remove the codes from your Start() method. Check the documentation here: https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html

  2. This is not really an error, but a best practice. After checking for tags, you can do a null check to avoid Exception error.

You can do:

if(other.gameObect != null)

Before calling this code:

UpdateUI();
  1. If you're incrementing by 1, you can do: UIVal1 , or UIVal1 = 1.

CodePudding user response:

You made a mistake when incrementing the UIVAL1, the is the right way :

void UpdateFloat()
        {
            UIVal1 = UIVal1  1;
        }
  • Related