微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。