我无法设置自定义属性 Unity PUN 2



我正在制作一款多人游戏,每个人都有黄金或炸弹变量。我想用自定义属性设置它,但我得到了空引用错误:
NullReferenceException: Object reference not set to an instance of an object

这是我的PlayerController代码:

public class PlayerController : MonoBehaviourPunCallbacks
{
public ExitGames.Client.Photon.Hashtable myCustomProperties = new ExitGames.Client.Photon.Hashtable();
public Rigidbody rb;
public Player player;
public int playerID;
public int[] goldArray = { 1, 2, 5, 10, 20, 30, 50, 75, 100 };
private void Start()
{
SetCustomProps();
Debug.Log(PhotonNetwork.LocalPlayer.CustomProperties);
}

/*private void OnTriggerEnter(Collider other)
{

if (Input.GetKeyDown("space"))
{
Debug.Log("space pressed!");
Destroy(other.gameObject);
//swapBomb(other);
}
}*/
/*private void swapBomb(Collider other)
{
}*/
public void SetCustomProps()
{
int gold = (int)PhotonNetwork.LocalPlayer.CustomProperties["Gold"];    //error
gold = goldArray[Random.Range(0, goldArray.Length)] * 10;
myCustomProperties.Add("Gold", gold);
bool bomb = (bool)PhotonNetwork.LocalPlayer.CustomProperties["Bomb"];
bomb = false;
myCustomProperties.Add("Bomb", bomb);
PhotonNetwork.LocalPlayer.SetCustomProperties(myCustomProperties);   //error
}
}

感谢您选择光子!

最初,玩家没有";金";以及";炸弹;属性。因此,在尝试获取和强制转换它们时会出现NullReferenceException。

但是,你真的需要先获得旧的或当前的价值观吗?看起来你无论如何都会凌驾于这些之上。

因此,我将首先使用ContainsKeyTryGetValue来检查它们是否存在。

示例1:

public void SetCustomProps()
{
object temp;
if (PhotonNetwork.LocalPlayer.CustomProperties.TryGetValue("Gold", out temp))
{ 
int gold = (int)temp;

示例2:

if (PhotonNetwork.LocalPlayer.CustomProperties.ContainsKey("Bomb"))
{ 
bool bomb = (bool)PhotonNetwork.LocalPlayer.CustomProperties["Bomb"];

旁注:

  • 最好将静态字段或常量用于自定义属性键字符串,而不是到处使用硬编码字段或常量。这将帮助您避免密钥不匹配的问题,因为它们区分大小写
  • 如果myCustomProperties字段仅在SetCustomProperties内部使用,那么仅将其用作局部变量可能是有意义的
  • 在使用单独的方法连接房间之前,可能需要设置初始自定义属性。通过这种方式,您最终会得到join-directly上的初始值

最新更新