I am using NetworkList to store a list of player scores. I initially ran into a memory leak when I initialized the list in its declaration, as is expected based on the docs. However, even after moving the initialization into Awake(), I am still getting memory leaks.
After doing some searching, it seems like calling Dispose() on the list at some point might be a solution. I tried this but then ran into other issues regarding “accessing a disposed object”.
Is this the proper solution, and I just need to rework my code to work with this? Or is there a better solution?
using UnityEngine;
using Unity.Netcode;
using System.Collections.Generic;
using TMPro;
public class PlayerScoreManager : NetworkBehaviour
{
public NetworkList<int> playerScores;
[SerializeField] private List<TMP_Text> playerScoreTexts;
private void Awake()
{
playerScores = new NetworkList<int>();
}
public override void OnNetworkSpawn()
{
NetworkManager.Singleton.OnConnectionEvent += OnClientConnected;
base.OnNetworkSpawn();
}
public override void OnNetworkDespawn()
{
NetworkManager.Singleton.OnConnectionEvent -= OnClientConnected;
base.OnNetworkDespawn();
}
public override void OnDestroy()
{
//playerScores.Dispose(); // I have been playing around with using Dispose
base.OnDestroy();
}
private void OnClientConnected(NetworkManager networkManager, ConnectionEventData connectionData)
{
if (connectionData.EventType != ConnectionEvent.ClientConnected) return;
if (IsServer)
{
Debug.Log("Adding a player score");
playerScores.Add(0);
}
}
// Player index starts at 0
public void IncrementPlayerScore(ulong clientId, int step = 1)
{
if (!IsServer) return;
int playerIndex = (int)clientId;
if (playerIndex > playerScores.Count - 1)
{
Debug.LogWarning("Attempt to add score to non-existent player");
return;
}
Debug.Log("Incrementing player score");
playerScores[playerIndex] += step;
}
private void UpdateScoreUi()
{
for (int i = 0; i < playerScores.Count; i++)
{
TMP_Text playerScoreText = playerScoreTexts[i];
playerScoreText.text = playerScores[i].ToString();
}
}
private void Update()
{
if (IsClient && IsSpawned)
{
UpdateScoreUi();
}
}
}