RiftMayhem/Assets/Scripts/UI/ExperienceBarUI.cs
Pedro Gomes c2b076ff5a Bugfixing null references corner cases
- fixed possible null on show tooltip of consumable item that was just used.
- fixed an issue preventing all characters from being loaded on character list if one in between was pointing to a null reference in playerprefs
2024-08-05 00:40:08 +01:00

73 lines
2.0 KiB
C#

using Kryz.CharacterStats.Examples;
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class ExperienceBarUI : MonoBehaviour
{
[Header("Components:")]
[SerializeField] private TMP_Text level;
[SerializeField] private TMP_Text nextLevel;
[SerializeField] private TMP_Text experienceBar;
[SerializeField] private Image experienceBarFill;
[Header("Listeners:")]
[SerializeField] private GameEventListener_PhotonView onPlayerSpawned;
PlayerCharacterStats player;
float startingWidth;
float currentFill;
RectTransform rectFill;
RectMask2D mask;
Vector4 sizeFill = new Vector4();
private void Awake()
{
onPlayerSpawned.Response.AddListener(DependancyInjection);
rectFill = experienceBarFill.GetComponent<RectTransform>();
mask = experienceBarFill.GetComponent<RectMask2D>();
startingWidth = rectFill.rect.width;
}
private void DependancyInjection(PhotonView spawnedPlayer)
{
if (!spawnedPlayer.IsMine) return;
player = ((RiftPlayer)spawnedPlayer.Owner.TagObject).GetComponent<PlayerCharacterStats>();
player.level.OnLevelUpEvent.AddListener(UpdateLevelText);
player.level.OnExperienceChanged.AddListener(UpdateLevelText);
UpdateLevelText();
}
public void UpdateLevelText()
{
level.text = player.level.currentLevel.ToString();
nextLevel.text = (player.level.currentLevel + 1).ToString();
experienceBar.text = $"{player.level.GetCurrentExperience().ToString("F1")}/{player.level.FinalExperienceThreshold.ToString("F1")}";
SetCurrentFill();
}
private void SetCurrentFill()
{
currentFill = player.level.GetCurrentExperience() / player.level.FinalExperienceThreshold;
sizeFill.x = 0;
sizeFill.y = 0;
sizeFill.z = startingWidth - (currentFill * startingWidth);
sizeFill.w = 0;
mask.padding = sizeFill;
}
}