How do I make my score system work?

I am trying to add a point to the scoreboard everytime the ball hits a trigger but it will not run properly and I am unsure why. Help please? I’m new to unity btw.,I trying to add 1 to the scoreboard which is a text but it won’t let me. Im new to coding btw.

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

public class ScoreManager : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log("Trigger!");
        GameObject scoreBoard = GameObject.FindWithTag("Score");
        score = scoreBoard.GetComponent<Text>();
        int point = 1;
        score = score + 1;


    }
}

You got a few things mixed up. Lets take a look at the variables.

  1. As peer your code score inst being probably set because it has no type (int, string, float)

  2. scoreBoard.GetComponent() is doing exactly that, getting the COMPONENT text, and not what is written in the component, what you are getting is the component you see in the inspector with all those options like Bold font size alignment etc. Therefore score is not a string but a Text object

  3. Even if it was a string you cant sum a number integer to a number that is written (a string) without first converting the string to a number.
    Lets try to fix what you have but I want you to try and implement some improvements after.

    public class ScoreManager : MonoBehaviour
    {
    private void OnTriggerEnter2D(Collider2D collision)
    {
    Debug.Log(“Trigger!”);
    GameObject scoreBoard = GameObject.FindWithTag(“Score”);
    //A variable type string
    //scoreBoard.GetComponent() gets the Text component, the .text grabs what is written in the Text component
    string score = scoreBoard.GetComponent().text;
    int point = 1;
    //Parses the string score to an integer and sums to point
    int scoreInt = int.Parse(score) + point;
    //Parses the integer scoreInt to string
    score = scoreInt.ToString();
    }
    }

That should work, but it aint based. Try the following to improve the code

  1. Make a integer variable “scoreTotal” and have it store the player’s score, that way you dont have to parse the string every time you need to increase the score, instead you just sum to scoreTotal and write that to score
  2. Check the tag of the collision so you can have different types of ball give different amounts of score
  3. Create a variable “Text score” at the start of the script and have it setup to the component only once, that way you avoid making a double search (Right now you find the scoreBoard and them you grab its component, you can just assign the component to a variable from the get go). This many searches will slow down your game if 100 balls hit the player in a sort amount of time.