我无法设置自定义属性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内部使用,则仅在其中将其用作局部变量可能有意义。
  • 也许您需要先设置初始自定义属性,然后再以单独的方法加入房间。这样,您最终会在直接加入时获得初始值。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...