Hotgun2222 2023-08-03 14:06 采纳率: 0%
浏览 74
已结题

Unity报空,获取不了实例NullReferenceException: Object reference not set to an instance of an object

BagController.SetBagItemListHandler(CurrentUserData);这行报空
我检查了服务器有没有给这个CurrentUserData.List赋值,也没问题,检查了有没有传过来这个CurrentUserData.List_Bag,也传过来了,而且我在客户端Debug了查了下List_Bag里有没有值,也有啊,没问题呀,而且上面都好好的,那些角色名啥的都没问题
经过排查发现BagController.SetBagItemListHandler这个报空,不知道为啥获取不到BagController,我也做了静态了
代码片段1:
BagController.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

///<summary>

///<summary>
public class BagController:MonoBehaviour
{
    private List<BagItem> TempBagItemList = new List<BagItem>();//临时的BagItemList
    public int geziCount = 22;//背包格子总数
    public GameObject go_Bag;//GameObject类型的背包(每个格子的父物体)
    private List<BagItem> _bagItemList;
    public delegate void dele_SetBagItemList(List<int> list);
    public static dele_SetBagItemList SetBagItemListHandler;
    private void Start()
    {
        SetBagItemListHandler += SetBagItemList;
    }
    private List<BagItem> BagItemList
    {
        get
        {
            return _bagItemList;
        }
        set
        {
            _bagItemList = value;
            for (int i = 0; i < geziCount; i++)
            {
                go_Bag.transform.GetChild(i).GetComponent<gezi>().Item = _bagItemList[i];
            }
        }
    }
    //将传来的数据放入BagItemList
    public void SetBagItemList(List<int> list)
    {
        for (int i = 0; i < list.Count; i++)
        {
            //id = 0 空
            if (list[i] == 0)
            {
                BagItem bagItem = new BagItem() { itemNumber = list[i], itemCount = 0, thingType = Things.ThingType.kong, index = i };
                TempBagItemList.Add(bagItem);
            }
            //101<=id<=220 装备
            else if (list[i] >= 101 && list[i] <= 220)
            {
                BagItem bagItem = new BagItem() { itemNumber = list[i], itemCount = 0, thingType = Things.ThingType.zhuangbei, index = i };
                TempBagItemList.Add(bagItem);
            }
            //1201<=id<=1240 技能书
            else if (list[i] >= 151 && list[i] <= 210)
            {
                BagItem bagItem = new BagItem() { itemNumber = list[i], itemCount = 0, thingType = Things.ThingType.jinengshu, index = i };
                TempBagItemList.Add(bagItem);
            }
            //1001<=id<=1103 药品
            else if (list[i] >= 211 && list[i] <= 220)
            {
                int id = int.Parse(list[i].ToString().Substring(0, 3));//传过来的int类型变量前三位为id
                int count = int.Parse(list[i].ToString().Substring(4, 2));//传过来的int类型变量后两位为其数量
                BagItem bagItem = new BagItem() { itemNumber = id, itemCount = count, thingType = Things.ThingType.yaoping, index = i };
                TempBagItemList.Add(bagItem);
            }
        }
        BagItemList = TempBagItemList;
    }
}


代码片段2:
peer.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TGClient;
using System;
using static Assets.Scripts.Enum;
using Newtonsoft.Json;
using Assets.Scripts;
///<summary>

///<summary>
public class peer : PeerBase
{
    CurrentUserData CurrentUserData = new CurrentUserData();
    /// <summary>
    /// 连接服务器成功时
    /// </summary>
    /// <param name="message"></param>
    public override void OnConnected(string message)
    {
        Debug.Log("服务器连接成功");
    }
    /// <summary>
    /// 与服务器断开连接时
    /// </summary>
    /// <param name="connectException"></param>
    public override void OnDisConnect(Exception connectException)
    {
        Debug.Log("服务器断开连接");
    }
    /// <summary>
    /// 接收服务器事件时
    /// </summary>
    /// <param name="eventCode"></param>
    /// <param name="dict"></param>
    public override void OnEvent(short eventCode, Dictionary<short, object> dict)
    {
        Debug.Log("客户端收到事件,事件代码是" + eventCode);
    }
    /// <summary>
    /// 连接服务器异常时
    /// </summary>
    /// <param name="exception"></param>
    public override void OnException(Exception exception)
    {
        Debug.Log("连接服务器异常:" + exception.ToString());
    }
    /// <summary>
    /// 接收服务器相应时
    /// </summary>
    /// <param name="opreationCode"></param>
    /// <param name="response"></param>
    public override void OnOperationResponse(short opreationCode, ReceiveResponse response)
    {
        Debug.Log("客户端收到响应,相应代码是:" + opreationCode);
        OpCode opCode = (OpCode)opreationCode;
        //成功
        if(response.returnCode == 0)
        {
            switch (opCode)
            {
                case OpCode.dialog:
                    break;
                case OpCode.login:
                    Debug.Log(response.parameters[DicKey.login]);
                    //从服务器传入数据到CurrentUserData实例(初始化)
                    object o_characterdata = response.parameters[DicKey.userdata];
                    string str_characterdata = JsonConvert.SerializeObject(o_characterdata);
                    CurrentUserData = JsonConvert.DeserializeObject<CurrentUserData>(str_characterdata);
                    //初始化大厅text
                    UIController.getText_lobby_Handler(CurrentUserData.CharacterName, CurrentUserData.sex, CurrentUserData.coin.ToString(), CurrentUserData.level.ToString(), CurrentUserData.maxHealth.ToString(), CurrentUserData.maxzhenqi.ToString(), CurrentUserData.attack.ToString(), CurrentUserData.attackInterval.ToString(), CurrentUserData.defence.ToString(), CurrentUserData.physical.ToString(), CurrentUserData.toukui.ToString(), CurrentUserData.yifu.ToString(), CurrentUserData.zhandouli.ToString());
                    //初始化人物数值面板text
                    UIController.instance.getText_peopleValuesPanel(CurrentUserData.CharacterName,CurrentUserData.sex,CurrentUserData.coin.ToString(),CurrentUserData.level.ToString(), CurrentUserData.maxHealth.ToString(), CurrentUserData.attack.ToString(), CurrentUserData.defence.ToString(), CurrentUserData.maxzhenqi.ToString(), CurrentUserData.xp.ToString(), CurrentUserData.physical.ToString(), CurrentUserData.zhandouli.ToString());
                    //显示大厅
                    UIController.AfterLogin_Handler();
                    if (CurrentUserData.List_Bag[0] == 161)
                    {
                        Debug.Log(11111);
                    }
                    if (CurrentUserData.userSkill.九天玄女)
                    {
                        Debug.Log(22222);
                    }
                    if (CurrentUserData != null)
                    {
                        Debug.Log(3333333);
                        if(BagController.SetBagItemListHandler!=null)
                        Debug.Log(444444);
                        if (UIController.afterCreateCharacter_Handler != null)
                        {
                            Debug.Log(5555555);
                        }
                        //初始化背包信息
                        BagController.SetBagItemListHandler(CurrentUserData.List_Bag);
                    }
                    break;
                case OpCode.buyThing:
                    break;
                case OpCode.register:
                    Debug.Log(response.parameters[DicKey.register]);
                    object o_userdata = response.parameters[DicKey.userdata];
                    string str_userdata = JsonConvert.SerializeObject(o_userdata);
                    CurrentUserData = JsonConvert.DeserializeObject<CurrentUserData>(str_userdata);
                    UIController.AfterRegister_Handler();
                    break;
                case OpCode.createCharacter:
                    Debug.Log("创建角色成功!");
                    //从服务器传入数据到CurrentUserData实例(初始化)
                    object o_characterData = response.parameters[DicKey.userdata];
                    string str_characterData = JsonConvert.SerializeObject(o_characterData);
                    CurrentUserData = JsonConvert.DeserializeObject<CurrentUserData>(str_characterData);
                    //初始化大厅text
                    UIController.getText_lobby_Handler(CurrentUserData.CharacterName, CurrentUserData.sex, CurrentUserData.coin.ToString(), CurrentUserData.level.ToString(), CurrentUserData.maxHealth.ToString(), CurrentUserData.maxzhenqi.ToString(), CurrentUserData.attack.ToString(), CurrentUserData.attackInterval.ToString(), CurrentUserData.defence.ToString(), CurrentUserData.physical.ToString(), CurrentUserData.toukui.ToString(), CurrentUserData.yifu.ToString(), CurrentUserData.zhandouli.ToString());
                    //初始化人物数值面板text
                    UIController.instance.getText_peopleValuesPanel(CurrentUserData.CharacterName, CurrentUserData.sex, CurrentUserData.coin.ToString(), CurrentUserData.level.ToString(), CurrentUserData.maxHealth.ToString(), CurrentUserData.attack.ToString(), CurrentUserData.defence.ToString(), CurrentUserData.maxzhenqi.ToString(), CurrentUserData.xp.ToString(), CurrentUserData.physical.ToString(), CurrentUserData.zhandouli.ToString());
                    //显示大厅
                    UIController.afterCreateCharacter_Handler();
                    //初始化背包信息
                    BagController.SetBagItemListHandler(CurrentUserData.List_Bag);
                    break;
                case OpCode.updatePassword:
                    //修改CurrentUserData类里的password
                    CurrentUserData.password = response.parameters[DicKey.newPassword].ToString();
                    Debug.Log(response.parameters[DicKey.updatePassword]);
                    UIController.instance.go_界面_修改密码.SetActive(false);
                    break;
            }
        }
        //失败
        else
        {
            switch (opCode)
            {
                case OpCode.dialog:
                    break;
                case OpCode.login:
                    Debug.Log(response.parameters[DicKey.login]);
                    break;
                case OpCode.buyThing:
                    break;
                case OpCode.register:
                    Debug.Log(response.parameters[DicKey.register]);
                    break;
                case OpCode.updatePassword:
                    Debug.Log(response.parameters[DicKey.error]);
                    break;
            }
        }
    }
}


运行结果截图:

img


经过排查发现

     if(BagController.SetBagItemListHandler!=null)
                        Debug.Log(444444);

这个444444输出不出来,说明BagController.SetBagItemListHandler=null,但是看了又看不知道为啥会这样,不知道怎么修改,还希望有没有人能帮我看看怎么修改,谢谢
Unity版本为2020.3.41

  • 写回答

14条回答 默认 最新

  • Leodong. 2023-08-03 14:46
    关注
    获得0.60元问题酬金

    用单例试试呢。在BagController中添加一个静态变量,确保只有一个BagController实例。


    如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

    评论

报告相同问题?

问题事件

  • 系统已结题 8月11日
  • 创建了问题 8月3日