【问题标题】:Can a coroutine in C# return a string value? [duplicate]C#中的协程可以返回字符串值吗? [复制]
【发布时间】:2020-12-22 04:07:51
【问题描述】:

我正在使用 Unity 和 C# 构建一个游戏,当玩家将鼠标悬停在项目上时,会调用 UnityWebRequest 来处理 SPARQL 查询。我想为查询输出的 JSON 响应返回一个字符串。我无法从协程中获取返回值。到目前为止,我已经尝试过使用“回调”,尽管我不完全确定它是如何工作的。在协程从 webrequest 中检索数据后,我想操纵 JSOn 响应。有谁知道如何让它工作或有任何提示?谢谢!!

调用协程的脚本

internal class HighlightSelectionResponse : MonoBehaviour, ISelectionResponse
{
    public TextMeshProUGUI gameText;
    public RESTGet rest;
    private static string itemName;
    private string URL;
    string returnData;

    public void OnSelect(Transform selection)
    {
        // this method only works if a query toggle is checked
        if (rest.queryUsage == true)
        {
            var itemName = selection.name.ToString();  // name of the gameobject
            var URL = rest.queryURL + itemName;
            Debug.Log(URL);

            // START COROUTINE
            StartCoroutine(rest.GetData2(URL, (value)=> { returnData = value; } ));
            Debug.Log(returnData);  <=== returns Null
        }
    }

使用协程编写脚本

public IEnumerator GetData2(string uri, System.Action<string> callback)
{
        UnityWebRequest webRequest = UnityWebRequest.Get(uri);
        // Call/Request website and wait to finish
        yield return webRequest.SendWebRequest();
        if (webRequest.isNetworkError || webRequest.isHttpError)
        {
            Debug.Log("No response from website");
        }
        else
        {
            //process web result             
            Debug.Log("Data retrieved!");
            callback(webRequest.downloadHandler.text);
    }
}

【问题讨论】:

    标签: c# unity3d coroutine


    【解决方案1】:

    Russopotomus 的回答更好,但我的做法是这样的:

    首先我创建将处理数据的函数或对象(在我的示例中,ObjectCtrl 正在接收 JSON 对象),然后我调用 CoRoutine 并将数据作为参数传递

    希望对某人有所帮助

    public class ObjectCtrl : MonoBehaviour
    {
        public string Id { get; set; }
        public string Label
        {
            get { return _details.Find("Name").GetComponent<Text>().text; }
            set
            {
                _details.Find("Name").GetComponent<Text>().text = value;
            }
        }
    
        public void SetData(JSONNode product)
        {
            Id = product["id"];
            Label = product["name"];
    
            // Add more fields here....
        }
    
    }
    
    
    public class ObjectCtrl : MonoBehaviour
    {
        protected void Start()
        {
            StartCoroutine(GetProductInfo(url));
        }
    
        public void SetData(JSONNode product)
        {
            Id = product["id"];
            Label = product["name"];
    
            // Add more fields here....
        }
    
        protected IEnumerator GetProductInfo(string uri)
        {
            UnityWebRequest www = UnityWebRequest.Get(uri);
            // Call/Request website and wait to finish
            yield return www.SendWebRequest();
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.LogError(www.error);
            }
            else
            {
                //Process web result             
                Debug.Log("Data retrieved!");
                JSONNode product = JSON.Parse(www.downloadHandler.text);
    
                // If the data is needed by a member I only need to call the member:
                SetData(product);
    
                // If the data is needed by another object i search for the object
                ObjectCtrl objCtrl = objContainer.GetComponent<ObjectCtrl>();
                objCtrl.SetData(product);
            }
        }
    }
    

    【讨论】:

    • 然后永远不要调用callback? ;)
    • 抱歉...已编辑
    • 这让事情变得更糟了 ;) .. OP 的代码中没有 ObjectCtrl .. 问题是为什么 Debug.Log 在 StartCoroutine 之后没有显示正确的值......你应该坚持Action&lt;string&gt;,但必须调用它并实际启动协程并传入相应的回调作为参数
    • 再次编辑,希望这样更清楚
    【解决方案2】:

    您遇到的问题是您尝试在 returnData 返回之前使用它。协程是一个异步函数,将在未来某个时间点终止,因此您必须在返回值完成后执行任何操作。这通常通过在回调中继续代码流来完成。例如:

                // START COROUTINE
                StartCoroutine(rest.GetData2(URL, (value) => {
                    // This function is called after GetData2 has completed.
                    returnData = value;
                    Debug.Log(returnData); // <=== logs value
                } ));
                // This code flow continues IMMEDIATELY AFTER we START COROUTINE,
                // and has not waited for GetData2 to complete, so it logs null
                Debug.Log(returnData);
    

    【讨论】:

      【解决方案3】:

      尝试使用ref 关键字并通过引用传递returnData:

      public void OnSelect(Transform selection)
          {
              // this method only works if a query toggle is checked
              if (rest.queryUsage == true)
              {
                  var itemName = selection.name.ToString();  // name of the gameobject
                  var URL = rest.queryURL + itemName;
                  Debug.Log(URL);
      
                  // START COROUTINE
                  StartCoroutine(rest.GetData2(URL, ref returnData));
                  Debug.Log(returnData); 
              }
          }
      
      public IEnumerator GetData2(string uri, ref string returnValue)
      {
              returnValue = "";
              UnityWebRequest webRequest = UnityWebRequest.Get(uri);
              // Call/Request website and wait to finish
              yield return webRequest.SendWebRequest();
              if (webRequest.isNetworkError || webRequest.isHttpError)
              {
                  Debug.Log("No response from website");
              }
              else
              {
                  //process web result             
                  Debug.Log("Data retrieved!");
                  returnValue = webRequest.downloadHandler.text;
          }
      }
      

      【讨论】:

      • 感谢您的回复!不幸的是,我得到了迭代器不能有 ref 参数的错误。
      猜你喜欢
      • 2020-02-26
      • 2019-05-11
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 2011-02-07
      相关资源
      最近更新 更多