experience gain unity code example

Example: experience gain unity

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

public class ExperienceGain : MonoBehaviour		
{
    XPBar xpBar;	// a simple class on a UI object with a slider(slider.minValue = argument passed through parameter, same for maxValue and value)
    float currentXp;
    float nextXpNeeded = 100;
    int playerLevel = 1;

    [SerializeField] Text currentLevelText = null;
    [SerializeField] Text nextLevelText = null;
    float xpGained = 0;
    [SerializeField] float xpBuildupSpeed = 20f;
    [SerializeField]float xpFactor = 1.1f;

    private void Awake()
    {
        xpBar = FindObjectOfType<XPBar>();
        xpBar.SetMaxSliderValue(nextXpNeeded);
        xpBar.SetSliderValue(currentXp);
    }

    private void Update()
    {
        if (xpGained >= nextXpNeeded)
        {
            LevelUp();
        }

        if (xpGained < currentXp)
        {
            xpGained += xpBuildupSpeed * Time.deltaTime;
            xpBar.SetSliderValue(xpGained);
        }
    }

    public void GainExperience(float experience)
    {
        currentXp += experience; 
    }

    public void LevelUp()
    {
        playerLevel++;
        currentXp -= xpGained; 
        xpGained = 0;

        xpBar.SetMinSliderValue(0);
        nextXpNeeded *= xpFactor;
        xpBar.SetMaxSliderValue(nextXpNeeded);
        xpBar.SetSliderValue(0);
        
        currentLevelText.text = playerLevel.ToString();
        nextLevelText.text = (playerLevel + 1).ToString();
    }
}