I have created my own Player Class containing a NetworkPlayer object and some Additional variables (Name, Level, Ping, …). It looks like this (shortened):
class Player
{
public NetworkPlayer NetPlayer;
public Player()
{
NetPlayer = new NetworkPlayer();
}
}
In the MonoBehaviour class in the same file, I’m creating some Instances of that Player Object:
private void Start()
{
ConnectedPlayers = new Player[32];
MyPlayerInstance = new Player();
MyPlayerInstance.NetPlayer = Network.player;
}
When a player joins the server, I wanted to assign his NetworkPlayer Instance to one of my ConnectedPlayers:
private void OnPlayerConnected(NetworkPlayer player)
{
ConnectedPlayers[PlayerCount].NetPlayer = new NetworkPlayer(); //just in case it didn't work before...
ConnectedPlayers[PlayerCount].NetPlayer = player;
}
Problem: The last line of code returns an NullReferenceException.
I have no idea why, when I got this error before, I mostly forgot to create the Instance using “new …”.
You didn’t create any of the player objects in your array.
This line:
ConnectedPlayers = new Player[32];
will create an array with 32 Player-references but those are all null because you have to create your Players too.
You have three options:
Create all 32 playerobjects in start and assign them to your array.
Create the playerobject when it’s needed (when a player joins).
Turn your Player class into a struct.
Sometimes it’s nice to be able to null such instances to indicate that this player isn’t used. But if your code needs to be able to access all 32 players you take solution 1 or 3
Solution1:
ConnectedPlayers = new Player[32];
for(int i = 0;i < ConnectedPlayers.Length; i++)
ConnectedPlayers *= new Player();*
Solution2: ---------- class Player { public NetworkPlayer NetPlayer;
public Player(NetworkPlayer aNetPlayer) { NetPlayer = aNetPlayer; } }
private void OnPlayerConnected(NetworkPlayer player) { ConnectedPlayers[PlayerCount] = new Player(player); } Solution3: ---------- struct Player { public NetworkPlayer NetPlayer; //NetworkPlayer is also a struct and therefore a value-type } private void OnPlayerConnected(NetworkPlayer player) { ConnectedPlayers[PlayerCount].NetPlayer = player; } ps. an array can get you in trouble when one of the first player leaves and a new one joins. Your playercount (i guess you increment it when someone joins and decrement it when one leaves) can’t not be used as index into the array since your array can get “fragmented”. For such a task i would suggest a List<Player> or maybe a Dictionary<NetworkPlayer,Player>. You can add and remove players easily.