whats casuses this "NullReferenceException: Object reference not set to an instance of an object"
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.UI;
using ExitGames.Client.Photon;
public class PlayerItems : MonoBehaviourPunCallbacks
{
[SerializeField] Text playerNameInput;
[SerializeField] GameObject leftButton;
[SerializeField] GameObject rightButton;
// Characeter Selection
Hashtable playerProperties = new Hashtable();
[SerializeField] Image playerAvatars;
[SerializeField] Sprite[] avatars;
Player player;
public void setPlayerInfo(Player playerName)
{
playerNameInput.text = playerName.NickName;
player = playerName;
updatePlayerItem(player);
}
public void ApplyLocalChanges()
{
leftButton.SetActive(true);
rightButton.SetActive(true);
}
public void onClickLeftArrow()
{
// I keep recieving "NullReferenceException: Object reference not set to an instance of an object" error
// on line 38 and 53. Does anyone know how to fix this
if ((int)playerProperties["playerAvatars"] == 0)
{
playerProperties["playerAvatars"] = avatars.Length - 1;
}
else
{
playerProperties["playerAvatars"] = (int)playerProperties["playerAvatars"] - 1;
}
PhotonNetwork.SetPlayerCustomProperties(playerProperties);
}
public void onClickRightArrow()
{
// I keep recieving "NullReferenceException: Object reference not set to an instance of an object" error
// on line 38 and 53.
if ((int)playerProperties["playerAvatars"] == avatars.Length - 1)
{
playerProperties["playerAvatars"] = 0;
}
else
{
playerProperties["playerAvatars"] = (int)playerProperties["playerAvatars"] + 1;
}
PhotonNetwork.SetPlayerCustomProperties(playerProperties);
}
public override void OnPlayerPropertiesUpdate(Player targetPlayer, ExitGames.Client.Photon.Hashtable changedProps)
{
if (player == targetPlayer)
{
updatePlayerItem(targetPlayer);
}
}
public void updatePlayerItem(Player player)
{
if (player.CustomProperties.ContainsKey("playerAvatars"))
{
playerAvatars.sprite = avatars[(int)player.CustomProperties["playerAvatars"]];
playerProperties["playerAvatar"] = (int)player.CustomProperties["playerAvatars"];
}
else
{
playerProperties["playerAvatar"] = 0;
}
}
}
Answers
-
"Object reference not set to an instance of an object".
This error can appears because that GameObject in the scene doesnt exist at this moment maybe it loads after.
1