原因:

       子线程调用了主线程才可以调用的方法

解决方案:

        用代理封装要执行的方法。由Unity Update调用。

    private void Update()
    {
        // if (notifierDataList.Count > 0)
        // {
        //     Notifier(notifierDataList[0]);
        //     //notifierDataList.RemoveAt(0);
        //     Debug.Log("NotifierList Count = "+notifierDataList.Count);
        //     notifierDataList.Clear();
        // }
        
        if (count != 0)
        {
            lock (locker) 
            {
                foreach (var a in notifierDataList)
                {
                    if (a != null)
                    {
                        Notifier(a);
                    }
                }
                Debug.Log("NotifierList Count = "+notifierDataList.Count);
                notifierDataList.Clear();
                count = 0;
            }
        }

    }

    private void Notifier(List<Vector2> notifierData)
    {
        CarpetManager.Instance.SetAllBallTrackPos(notifierData);
    }

    // Receive data, update packets received
    private void ReceiveData()
    {
        while (true)
        {
            try
            {
                IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = client.Receive(ref anyIP);
                string text = Encoding.UTF8.GetString(data);
                print(">> " + text);
                ProcessInput(text);
            }
            catch (Exception err)
            {
                print(err.ToString());
            }
        }
    }

    private void ProcessInput(string recvStr)
    {
        // PROCESS INPUT RECEIVED STRING HERE
        //pythonTest.UpdatePythonRcvdText(input); // Update text by string received from python
        if (!string.IsNullOrEmpty(recvStr))
        {
            Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(recvStr);
            var posList = new List<Rect>();
            foreach (var posRect in dic.Values.ToList())
            {
                var posVect = new Rect();
                // posVect.x = (float) ((JArray)posRect)[0];
                // posVect.y = (float) ((JArray)posRect)[1];
                posVect.x = (int) ((JArray) posRect)[0];
                posVect.y = (int) ((JArray) posRect)[1];
                posList.Add(posVect);
            }

            var posWarpedList = CarpetManager.Instance.GetWarpedPosList(posList);
            //notifierDataList.Add(posList);
            //notifierDataList.Insert(0, posWarpedList);
            lock (locker) 
            {
                notifierDataList.Add(posWarpedList);
                count++;
            }

        }
        
        if (!isTxStarted) // First data arrived so tx started
        {
            isTxStarted = true;
        }
    }

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐