Variable being replaced rather than added to.

Hey o. New to unity and have a newbie question. The following code is supposed to add to a player score whenever a ball enters a box. However, whenever a ball enters a box, the score just gets replaced. For example, if the score is 25, when the ball falls into the 10 point box, the score is set to 10 instead of 35. I’m using countNumber to set the score for each box in the inspector.

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

public class Counter : MonoBehaviour
{
    public Text CounterText;

    private int Count = 0;
    public int countNumber;

    private void Start()
    {
        Count = 0;
    }

    private void OnTriggerEnter(Collider other)
    {
        Count += countNumber;
        CounterText.text = "Count : " + Count;
        Debug.Log("Score is: " + Count);
    }
}

Do you have a bunch of these?

Each one of them has its own Count:

Not only that but each one will overwrite that Text field, if it is all the same field.

Are you instead looking to have a single Count (like a score) that each box contributes to?

This is typically handled by having a score manager or game manager that manages that one variable, and each box calls to add a value to it.

Check out tutorials on any game similar to this and you’ll see some type of centralized score tracker.

Alternatively, make your own simple score manager. Here’s two possible patterns:

ULTRA-simple static solution to a GameManager:

https://discussions.unity.com/t/855136/6

https://gist.github.com/kurtdekker/50faa0d78cd978375b2fe465d55b282b

OR for a more-complex “lives as a MonoBehaviour” solution…

Simple Singleton (UnitySingleton):

Some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

https://gist.github.com/kurtdekker/775bb97614047072f7004d6fb9ccce30

Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

https://gist.github.com/kurtdekker/2f07be6f6a844cf82110fc42a774a625

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

public void DestroyThyself()
{
   Destroy(gameObject);
   Instance = null;    // because destroy doesn't happen until end of frame
}

There are also lots of Youtube tutorials on the concepts involved in making a suitable GameManager, which obviously depends a lot on what your game might need.