I Need Help Applying Data From Firebase To My Leveling System In Unity - c#

I've created a leveling system for my game in Unity. I was able to store the level and XP amount in my Firebase database. I'm also able to display both the level and XP in gave and have it update in the database without having to manually save the data.
The problem is now that the xp bar I created that scales based on the amount of xp the user is not communicating with my database, only its self. It also resets all int variables to 0 when switching scenes or restarting the game.
My goal here is to have the progress bar update live based on the amount of xp that's stored in my database and to have it not reset after I switch scenes or reload the game.
Here's my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class LevelSystem
{
public event EventHandler OnExperienceChanged;
public event EventHandler OnLevelChanged;
private static readonly int[] experiencePerLevel = new[] {100, 120, 145, 175, 210, 250, 295, 345, 400, 460};
private int level;
private int experience;
private int experienceToNextLevel;
private TMP_Text xpText;
public LevelSystem()
{
level = 0;
experience = 0;
experienceToNextLevel = 100;
}
public void AddExperience(int amount)
{
if (!IsMaxLevel())
{
experience += amount;
while (!IsMaxLevel() && experience >= GetExperienceToNextLevel(level))
{
//Enough experience to level up
level++;
experience -= GetExperienceToNextLevel(level);
if(OnLevelChanged != null) OnLevelChanged(this, EventArgs.Empty);
}
if(OnExperienceChanged != null) OnExperienceChanged(this, EventArgs.Empty);
}
}
public int GetLevelNumber()
{
return level;
}
public int GetXpAmount()
{
return experience;
}
public float GetExperienceNormalized()
{
if (IsMaxLevel())
{
return 1f;
}
else
{
return (float)experience / GetExperienceToNextLevel(level);
}
}
public int GetExperience()
{
return experience;
}
public int GetExperienceToNextLevel()
{
return experienceToNextLevel;
}
public int GetExperienceToNextLevel(int level)
{
if (level < experiencePerLevel.Length)
{
return experiencePerLevel[level];
}
else
{
//Level invalid
Debug.Log("Level invalid: " + level);
return 100;
}
}
public bool IsMaxLevel()
{
return IsMaxLevel(level);
}
public bool IsMaxLevel(int level)
{
return level == experiencePerLevel.Length - 1;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Utilities.Mine;
public class LevelSystemAnimation
{
public event EventHandler OnExperienceChanged;
public event EventHandler OnLevelChanged;
private LevelSystem levelSystem;
private bool isAnimating;
private float updateTimer;
private float updateTimerMax;
private int level;
private int experience;
public LevelSystemAnimation(LevelSystem levelSystem)
{
SetLevelSystem(levelSystem);
updateTimerMax = .016f;
FunctionUpdater.Create(() => Update());
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
level = levelSystem.GetLevelNumber();
experience = levelSystem.GetExperience();
levelSystem.OnExperienceChanged += LevelSystem_OnExperienceChanged;
levelSystem.OnLevelChanged += LevelSystem_OnLevelChanged;
}
private void LevelSystem_OnLevelChanged(object sender, System.EventArgs e)
{
isAnimating = true;
}
private void LevelSystem_OnExperienceChanged(object sender, System.EventArgs e)
{
isAnimating = true;
}
public void Update()
{
if(isAnimating)
{
updateTimer += Time.deltaTime;
while (updateTimer > updateTimerMax)
{
updateTimer -= updateTimerMax;
UpdateTypeAddExperience();
}
}
}
private void UpdateTypeAddExperience()
{
if(level < levelSystem.GetLevelNumber())
{
//Local level under target level
AddExperience();
}
else
{
//Local level equals the target level
if (experience < levelSystem.GetExperience())
{
AddExperience();
}
else
{
isAnimating = false;
}
}
}
public void AddExperience()
{
experience++;
if (experience >= levelSystem.GetExperienceToNextLevel(level))
{
level++;
experience = 0;
if(OnLevelChanged != null) OnLevelChanged(this, EventArgs.Empty);
}
if(OnExperienceChanged != null) OnExperienceChanged(this, EventArgs.Empty);
}
public int GetLevelNumber()
{
return level;
}
public int GetXpAmount()
{
return experience;
}
public float GetExperienceNormalized()
{
if (levelSystem.IsMaxLevel(level))
{
return 1f;
}
else
{
return (float)experience / levelSystem.GetExperienceToNextLevel(level);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class LevelFunction : MonoBehaviour
{
public static LevelFunction instance;
[SerializeField]
private TMP_Text levelText;
[SerializeField]
private Image experienceBarImage;
[SerializeField]
private TMP_Text xpText;
private LevelSystem levelSystem;
private LevelSystemAnimation levelSystemAnimation;
private void SetExperienceBarSize(float experienceNormalized)
{
experienceBarImage.fillAmount = experienceNormalized;
}
private void SetLevelNumber(int levelNumber)
{
levelText.text = "L" + (levelNumber + 1);
}
private void SetXpAmount(int xpAmount)
{
xpText.text = "" + xpAmount;
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
}
public void SetLevelSystemAnimation(LevelSystemAnimation levelSystemAnimation)
{ //Set the LevelSystem object
this.levelSystemAnimation = levelSystemAnimation;
//Update the starting values
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
//Subscribe to the chnaged events
levelSystemAnimation.OnExperienceChanged += LevelSystemAnimation_OnExperienceChanged;
levelSystemAnimation.OnLevelChanged += LevelSystemAnimation_OnLevelChanged;
}
private void LevelSystemAnimation_OnLevelChanged(object sender, System.EventArgs e)
{
//Level changed, update text
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
}
private void LevelSystemAnimation_OnExperienceChanged(object sender, System.EventArgs e)
{
//Experience changed, update bar size
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class GainXpManager : MonoBehaviour
{
public static GainXpManager instance;
[SerializeField]
private Button collectButton;
[SerializeField]
private TMP_Text levelText;
[SerializeField]
private Image experienceBarImage;
[SerializeField]
private TMP_Text xpText;
public GameObject endGameResults;
private LevelSystem levelSystem;
private LevelSystemAnimation levelSystemAnimation;
private int level;
private int experience;
private void SetExperienceBarSize(float experienceNormalized)
{
experienceBarImage.fillAmount = experienceNormalized;
}
private void SetLevelNumber(int levelNumber)
{
levelText.text = "L" + (levelNumber + 1);
}
private void SetXpAmount(int xpAmount)
{
xpText.text = "" + xpAmount;
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
level = levelSystem.GetLevelNumber();
experience = levelSystem.GetExperience();
}
public void SetLevelSystemAnimation(LevelSystemAnimation levelSystemAnimation)
{ //Set the LevelSystem object
this.levelSystemAnimation = levelSystemAnimation;
//Update the starting values
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
//Subscribe to the chnaged events
levelSystemAnimation.OnExperienceChanged += LevelSystemAnimation_OnExperienceChanged;
levelSystemAnimation.OnLevelChanged += LevelSystemAnimation_OnLevelChanged;
}
private void LevelSystemAnimation_OnLevelChanged(object sender, System.EventArgs e)
{
//Level changed, update text
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
FirebaseManager.instance.ActivateXPUpdate();
}
private void LevelSystemAnimation_OnExperienceChanged(object sender, System.EventArgs e)
{
//Experience changed, update bar size
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
FirebaseManager.instance.ActivateXPUpdate();
}
public void AddXpToAccount()
{
endGameResults.SetActive(false);
levelSystem.AddExperience(25);
}
}
There's more code but I think the problem can be solved with these. Any suggestions would help.

Related

The problem is the disappearance of the player

I have one rather ambiguous problem in my C# (Unity) code. It lies in the fact that my player disappears because of the prescribed lines about the spawnpoint. Because of them, my player simply disappears when I run the game
The lines where the problem is possible are 22, 109-112. Please help me with this problem. Thank you very much in advance
But I need spawnpoint for further work. Thank you very much in advance!
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public static GameManager instance;
private void Awake()
{
if(GameManager.instance != null)
{
Destroy(gameObject);
Destroy(player.gameObject);
Destroy(floatingTextManager.gameObject);
Destroy(HUD);
Destroy(menu);
return;
}
instance = this;
SceneManager.sceneLoaded += LoadState;
SceneManager.sceneLoaded += OnSceneLoaded;
}
public List<Sprite> playerSprites;
public List<Sprite> weaponSprites;
public List<int> weaponPrices;
public List<int> xpTable;
public Player player;
public Weapon weapon;
public FloatingTextManager floatingTextManager;
public Animator misMenuAnim;
public RectTransform hitpointBar;
public GameObject HUD;
public GameObject menu;
public int pesos;
public int experience;
public void ShowText(string msg, int fontSize, Color color, Vector3 position, Vector3 motion, float duration)
{
floatingTextManager.Show(msg, fontSize, color, position, motion, duration);
}
public bool TryUpgradeWeapon()
{
if (weaponPrices.Count <= weapon.weaponLevel)
return false;
if(pesos >= weaponPrices[weapon.weaponLevel])
{
pesos -= weaponPrices[weapon.weaponLevel];
weapon.UpgradeWeapon();
return true;
}
return false;
}
public void OnHitpointChange()
{
float ratio = (float)player.hitpoint / (float)player.maxHitpoint;
hitpointBar.localScale = new Vector3(1, ratio, 1);
}
public int GetCurrentLevel()
{
int r = 0;
int add = 0;
while(experience >= add)
{
add += xpTable[r];
r++;
if (r == xpTable.Count)
return r;
}
return r;
}
public int GetXpToLevel(int level)
{
int r = 0;
int xp = 0;
while(r < level)
{
xp += xpTable[r];
r++;
}
return xp;
}
public void GrantXp(int xp)
{
int currLevel = GetCurrentLevel();
experience += xp;
if (currLevel < GetCurrentLevel())
OnLevelUp();
}
public void OnLevelUp()
{
player.OnLevelUp();
OnHitpointChange();
}
public void OnSceneLoaded(Scene s, LoadSceneMode mode)
{
player.transform.position = GameObject.Find("SpawnPoint").transform.position;
}
public void Respawn()
{
misMenuAnim.SetTrigger("Hide");
UnityEngine.SceneManagement.SceneManager.LoadScene("SampleScene");
player.Respawn();
}
public void SaveState()
{
string s = "";
s += "0" + "|";
s += pesos.ToString() + '|';
s += experience.ToString() + "|";
s += weapon.weaponLevel.ToString();
}
public void LoadState(Scene s, LoadSceneMode mode)
{
SceneManager.sceneLoaded += LoadState;
if (!PlayerPrefs.HasKey("SaveState"))
return;
string[] data = PlayerPrefs.GetString("SaveState").Split('|');
pesos = int.Parse(data[1]);
experience = int.Parse(data[2]);
player.SetLevel(GetCurrentLevel());
weapon.SetWeaponLevel(int.Parse(data[0]));
}
}
I have tried many ways over the course of a month, but none of them could solve the problem...

How to button enabled/disabled on Ironsource Rewarded Video

I have a button for showing rewarded advertisement. If the advertisement is loaded, I want to enable this button, also if the advertisement is not loaded, I want to disabled this button. But, the code is not working, When i have no internet connection, the button is always enabled. How can i do this issue?
Here is my code :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RewardedShop : MonoBehaviour
{
public static RewardedShop Instance { get; set; }
private void Awake()
{
Instance = this;
}
public string appkey;
public GameObject afterRewardedScreen, mainScreen;
public Button btnWatchSHOP;
public GameObject btnActive;
RewardedGameObject[] go;
// Start is called before the first frame update
void Start()
{
IronSource.Agent.shouldTrackNetworkState(true);
IronSourceEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvaibilityChangedEvent;
IronSourceEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
IronSourceEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
//IronSourceEvents.onRewardedVideoAdReadyEvent += OnRewardedVideoAdReady;
btnWatchSHOP.interactable = false;
}
public void showRewarded()
{
if (IronSource.Agent.isRewardedVideoAvailable())
{
counter = 0;
IronSource.Agent.showRewardedVideo("ShopRewarded");
}
}
void RewardedVideoAdClosedEvent()
{
IronSource.Agent.init(appkey, IronSourceAdUnits.REWARDED_VIDEO);
IronSource.Agent.shouldTrackNetworkState(true);
}
void RewardedVideoAvaibilityChangedEvent(bool available)
{
bool rewardedVideoAvailability = available;
BtnActive();
}
int counter = 0;
void RewardedVideoAdRewardedEvent(IronSourcePlacement ssp)
{
if (counter < 1)
{
RewardHandlerSHOP.Instance.Reward();
counter++;
}
}
public void Reward()
{
PlayerPrefs.SetInt("totalCoin", PlayerPrefs.GetInt("totalCoin") + 150);
GameObject.Find("TxtTotalSHOPCoin").GetComponent<Text>().text = PlayerPrefs.GetInt("totalCoin").ToString();
SoundManager.Instance.PlayEarnGoldSound();
}
public void BtnActive()
{
bool available = IronSource.Agent.isRewardedVideoAvailable();
if (available)
{
btnWatchSHOP.interactable = true;
}
else
{
btnWatchSHOP.interactable = false;
}
}
}

Unity Photon.Pun Connecting isues When Change Scene

Hello Guys i am working on a small project and I installed the room setup system in the lobby without any problems, and when we set up the room, it directs us to a 2D scene. Everything was exactly what I wanted until now, like the room scene among us. LoadScene("Game"); I added the code and assigned it to the button. When I press the button, the scene changes, but [my status text says connecting but never connected, it's always stuck connecting and therefore players cannot go on stage] I'll share my codes below, can you help me?
Network.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using Photon.Pun;
using Photon.Realtime;
public class Network : MonoBehaviourPunCallbacks
{
public Text StatusText;
public CameraFollow playerCamera;
public MasterClient masterClient;
private void Start()
{
StatusText.text = "Connecting";
PhotonNetwork.NickName = "Player" + Random.Range(0, 5000);
// CreatePlayerCamera();
}
public void GameScene()
{
StatusText.text = "Joined " + PhotonNetwork.CurrentRoom.Name;
PhotonNetwork.LoadLevel("Game");
}
private void CreatePlayerCamera()
{
playerCamera.target = PhotonNetwork.Instantiate("Player", new Vector3(
Random.Range(-5, 5),
Random.Range(-5, 5),
0), Quaternion.identity).transform;
if (PhotonNetwork.IsMasterClient)
{
masterClient.Initialize();
}
}
public override void OnConnectedToMaster()
{
StatusText.text = "Connected to Master / Joining room";
PhotonNetwork.JoinOrCreateRoom("GameRoom", new RoomOptions() { MaxPlayers = 4 }, null);
CreatePlayerCamera();
}
public override void OnJoinedRoom ()
{
StatusText.text = PhotonNetwork.CurrentRoom.Name;
playerCamera.target = PhotonNetwork.Instantiate("Player",
new Vector3(
Random.Range(-10, 10),
Random.Range(-10, 10),
0), Quaternion.identity).transform;
}
}
Lobbynetwork.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
public class LobbyNetworkManager : MonoBehaviourPunCallbacks
{
int number;
int number2;
public Text su;
private List<RoomItemUI> _roomList = new List<RoomItemUI> ();
[SerializeField] private RoomItemUI _roomItemUIPrefab;
[SerializeField] private Transform _roomListParent;
[SerializeField] private Text _statusField;
[SerializeField] private Button _leaveRoomButton;
[SerializeField] private InputField _roomInput;
[SerializeField] private InputField _joinInput;
[SerializeField] private RoomItemUI _playerItemUIPrefab;
[SerializeField] private Transform _playerListParent;
private List<RoomItemUI> _playerList = new List<RoomItemUI>();
private void Start()
{
Initialize();
Connect();
}
#region PhotonCallbacks
public override void OnConnectedToMaster()
{
Debug.Log("Connected to master server");
PhotonNetwork.JoinLobby();
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
UpdateRoomList(roomList);
}
public override void OnDisconnected(DisconnectCause cause)
{
Debug.Log("Disconnect");
}
public override void OnJoinedLobby()
{
Debug.Log("Joined Lobby!");
}
public override void OnJoinedRoom()
{
_statusField.text = "Joined " + PhotonNetwork.CurrentRoom.Name;
Debug.Log("Joined Room " + PhotonNetwork.CurrentRoom.Name);
MoveScene();
// _leaveRoomButton.interactable = true;
UpdatePlayerList();
}
private void MoveScene()
{
PhotonNetwork.LoadLevel("Room_Scene");
}
public override void OnLeftRoom()
{
_statusField.text = "Lobby";
Debug.Log("Left Room");
_leaveRoomButton.interactable = false;
UpdatePlayerList();
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
UpdatePlayerList();
}
public override void OnPlayerLeftRoom(Player otherPlayer)
{
UpdatePlayerList();
}
#endregion
private void Initialize()
{
_leaveRoomButton.interactable = false;
}
private void Connect()
{
PhotonNetwork.NickName = "Player" + Random.Range(0, 5000);
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.AutomaticallySyncScene = true;
}
private void UpdateRoomList(List<RoomInfo> roomList)
{
//Clear the current list of rooms
for (int i =0; i < _roomList.Count; i++)
{
Destroy(_roomList[i].gameObject);
}
_roomList.Clear();
// Generate a new list with the updated info
for (int i = 0; i < roomList.Count; i++)
{
//skip empty rooms
if(roomList[i].PlayerCount == 0) { continue; }
RoomItemUI newRoomItem = Instantiate(_roomItemUIPrefab);
newRoomItem.LobbyNetworkParent = this;
newRoomItem.SetName(roomList[i].Name);
newRoomItem.transform.SetParent(_roomListParent);
_roomList.Add(newRoomItem);
}
}
private void UpdatePlayerList()
{
//Clear the current player list
//clear current list of room
for (int i = 0; i < _playerList.Count; i++)
{
Destroy(_playerList[i].gameObject);
}
_playerList.Clear();
if(PhotonNetwork.CurrentRoom == null) { return; }
//Generate a new list of players
foreach(KeyValuePair<int, Player> player in PhotonNetwork.CurrentRoom.Players)
{
RoomItemUI newPlayerItem = Instantiate(_playerItemUIPrefab);
newPlayerItem.transform.SetParent(_playerListParent);
newPlayerItem.SetName(player.Value.NickName);
_playerList.Add(newPlayerItem);
}
}
public void JoinRoom(string roomName)
{
PhotonNetwork.JoinRoom(roomName);
}
public void CreateRoom()
{
number = Random.Range(1000, 9000);
number2 = Random.Range(100, 800);
PhotonNetwork.CreateRoom("Su" + number + "TR" + number2, new RoomOptions() { MaxPlayers = 4 }, null);
/* if (string.IsNullOrEmpty(_roomInput.text) == false)
{
PhotonNetwork.CreateRoom(_roomInput.text + number, new RoomOptions() { MaxPlayers = 4 }, null);
} */
MoveScene();
}
public void JoinWitchCode ()
{
PhotonNetwork.JoinRoom(_joinInput.text);
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
}
}
Check my video
Youtube

Unity 2d İ had some error ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection

Hello guys I'm newbie in unity and c# i was trying make little game but i have a an error i cant fix that can you help me? and whats wrong? you explain so I can learn? I'm making a mistake somewhere but I don't understand where...
I also looked at the friends who got the same error in the forums, but I could not find the relevance of what was said with my code.I also made these codes with the things I learned on youtube, so if there are mistakes, please excuse me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
public class LobbyNetworkManager : MonoBehaviourPunCallbacks
{
int number;
public Text su;
private List<RoomItemUI> _roomList = new List<RoomItemUI>();
[SerializeField] private RoomItemUI _roomItemUIPrefab;
[SerializeField] private Transform _roomListParent;
[SerializeField] private Text _statusField;
[SerializeField] private Button _leaveRoomButton;
private void Start()
{
Initialize();
Connect();
}
#region PhotonCallbacks
public override void OnConnectedToMaster()
{
Debug.Log("Connected to master server");
PhotonNetwork.JoinLobby();
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
UpdateRoomList(roomList);
}
public override void OnDisconnected(DisconnectCause cause)
{
Debug.Log("Disconnect");
}
public override void OnJoinedLobby()
{
Debug.Log("Joined Lobby!");
}
public override void OnJoinedRoom()
{
_statusField.text = "Joined" + PhotonNetwork.CurrentRoom.Name;
Debug.Log("Joined Room " + PhotonNetwork.CurrentRoom.Name);
_leaveRoomButton.interactable = true;
}
public override void OnLeftRoom()
{
_statusField.text = "Lobby";
Debug.Log("Left Room");
_leaveRoomButton.interactable = false;
}
#endregion
private void Initialize()
{
_leaveRoomButton.interactable = false;
}
private void Connect()
{
PhotonNetwork.NickName = "Player" + Random.Range(0, 5000);
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.AutomaticallySyncScene = true;
}
private void UpdateRoomList(List<RoomInfo> roomList)
{
//clear current list of room
for (int i = 0; i < roomList.Count; i++)
{
Destroy(_roomList[i].gameObject);
}
_roomList.Clear();
//Generate a new list with the updated info
for(int i = 0; i < roomList.Count; i++)
{
//skip empty rooms
if(roomList[i].PlayerCount == 0) { continue; }
RoomItemUI newRoomItem = Instantiate(_roomItemUIPrefab);
newRoomItem.LobbyNetworkParent = this;
newRoomItem.SetName(roomList[i].Name);
newRoomItem.transform.SetParent(_roomListParent);
_roomList.Add(newRoomItem);
}
}
public void JoinRoom(string roomName)
{
PhotonNetwork.JoinRoom(roomName);
}
public void CreateRoom()
{
number = Random.Range(1000000, 9999999);
PhotonNetwork.CreateRoom(su.text + number, new RoomOptions() { MaxPlayers = 4 }, null);
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class RoomItemUI : MonoBehaviour
{
public LobbyNetworkManager LobbyNetworkParent;
[SerializeField] private Text _roomName;
public void SetName(string roomName)
{
_roomName.text = roomName;
}
public void OnJoinPressed()
{
LobbyNetworkParent.JoinRoom(_roomName.text);
}
}

ERROR the set accessor is inaccessible - Deducting user's score as currency

I have a score manager which tracks down your amount of points. And With these points I want the user to be able to purchase upgrades for his character.
But every time I try to access the user's current score I keep getting the same error message.
If you look at the Upgrademenu Document underneath you can see that I'm trying to do the following " // ScoreManager.Score -= upgradeCost; " The // is there because when I activate it I get the error message:
The property or indexer 'ScoreManager.Score' cannot be used in this context because the set accessor is inaccessible.
ScoreManager
using UnityEngine;
using System;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager Instance { get; private set; }
public static int Score { get; private set; }
public int HighScore { get; private set; }
public bool HasNewHighScore { get; private set; }
public static event Action<int> ScoreUpdated = delegate {};
public static event Action<int> HighscoreUpdated = delegate {};
private const string HIGHSCORE = "HIGHSCORE";
// key name to store high score in PlayerPrefs
void Awake()
{
if (Instance)
{
DestroyImmediate(gameObject);
}
else
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
Reset();
}
public void Reset()
{
// Initialize score
Score = 0;
// Initialize highscore
HighScore = PlayerPrefs.GetInt(HIGHSCORE, 0);
HasNewHighScore = false;
}
public void AddScore(int amount)
{
Score += amount;
// Fire event
ScoreUpdated(Score);
if (Score > HighScore)
{
UpdateHighScore(Score);
HasNewHighScore = true;
}
else
{
HasNewHighScore = false;
}
}
public void UpdateHighScore(int newHighScore)
{
// Update highscore if player has made a new one
if (newHighScore > HighScore)
{
HighScore = newHighScore;
PlayerPrefs.SetInt(HIGHSCORE, HighScore);
HighscoreUpdated(HighScore);
}
}
}
UpgradeMenu
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UpgradeMenu : MonoBehaviour
{
[SerializeField]
private Text accuracyText;
[SerializeField]
private Text speedText;
[SerializeField]
private Text damageText;
[SerializeField]
private Weapon weapon;
[SerializeField]
public Projectile projectile;
[SerializeField]
private Player player;
[SerializeField]
private int upgradeCost = 50;
void start ()
{
}
void OnEnable()
{
UpdateValues();
}
void UpdateValues ()
{
}
public void UpgradeArmor ()
{
Health.maxHealth += 2;
// ScoreManager.Score -= upgradeCost;
UpdateValues();
}
public void UpgradeSouls ()
{
EnemySlime.ScoreOnDeath += 1;
EnemySkeleton.ScoreOnDeath += 1;
// ScoreManager.Score -= upgradeCost;
UpdateValues();
}
public void UpgradeDamage ()
{
Projectile.DamageOnHit += 1;
// ScoreManager.Score -= upgradeCost;
UpdateValues();
}
}
You can't assign a value to Score from outside the class if its set accessor is set to private. Set it to public or make a method on the ScoreManager class to perform the deduction.

Categories