Help getting this to work

Hello, i am starting with unity and i am make a really simple game, i am trying to make an adventure game in 2d the only interactuable item in my scenes are buttons.
My idea is that each time I click one of this button depending witch one the player will get a point or lose a point so at the end i can change what ending the player get.
I have the following code:
-I have this to create the variable that will tell me the “score” of the player:

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

public class global : MonoBehaviour
{

    public static int loadFinal = 0;

}

-I have this added in the on click, in the button, technically this will increse in one the “score”:

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

public class add : MonoBehaviour
{

    // Start is called before the first frame update
    void Start()
    {
        global.loadFinal = global.loadFinal + 1;
        //global.loadFinal = global.loadFinal - 1;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

I am a bit lose with all this, what i am missing?

You call a function from the OnClick on the button. So you’ll need to add a function to your “add” script that is like “OnClick()” with the score increase code and then call that from the button click event.

However, I wouldn’t advise making a separate class for adding. To add is a function, and should really be part of some overall score manager that also has functions like “Subtract()”. That brings me to your naming conventions as well. Always start a class with a capital letter. It doesn’t affect functionality, but it is neater, looks more professional and makes things easier to disambiguate.

Something more like:

public class ScoreManager : MonoBehaviour
{
    public int Score { get; private set; }

    public void IncreaseScore(int amount) {
        // Might want to do some clamping here
        Score += amount;
    }

    public void DecreaseScore(int amount) {
        Score -= amount;
    }
}
1 Like