【问题标题】:Enumerator Start Function, Return Yield枚举器启动函数,返回产量
【发布时间】:2017-05-11 23:08:50
【问题描述】:

我目前正在研究统一,我正在尝试使用 WWW 类从 Web 下载数据。我的代码如下。

  IEnumerator Awake()
{
    WWW imgLinks = new WWW(imgConnection); //Here I am trying to download image links.
    yield return imgLinks; //here image URL are supposed to be downloaded.

    string imgLinkSring = imgLinks.text;
    imgLinksArray = imgLinkSring.Split(';'); //and they are splitted by ";"

    //---

    string _imgURL = "No data.";
    string _tag = "";
    for (int i = 0; i < imgLinksArray.Length; i++)
    {
        if (imgLinksArray[i].Contains("tag:"))
        {

            _tag = GetdataValue(imgLinksArray[i], "tag:");
            _imgURL = GetdataValue(imgLinksArray[i], "name:");
            if (_imgURL.Contains("|")) _imgURL = _imgURL.Remove(_imgURL.IndexOf("|"));
            if (_tag.Contains("|")) _imgURL = _imgURL.Remove(_imgURL.IndexOf("|"));

            WWW imgTextures = new WWW(domainName + "showImage.php?name=" + _tag); //and here imageTextures are supposed to be downloaded by the URL's I downloade in the beginning.  
            yield return imgTextures;
            tex = imgTextures.texture;
            textureDatas2.Add(_tag, tex);

        }

    }


}

问题是,如果我的代码中没有 Update(),这可以正常工作。当我有 Update() 时,代码从 yield return imgLinks; 跳转到 Update 函数,并在 Update 中运行代码,然后完成 start 函数。

我想要的是,完成运行 Start 功能,然后开始运行 Update 功能。

我该怎么办?

【问题讨论】:

  • 更新每帧运行一次。如果您的 start 方法产生并需要时间,那么 Update 绝对会在等待发生时被调用。
  • @Draco18s 那么我怎样才能实现我想要的呢?
  • 您需要等待协程完成,然后才能对其数据进行任何操作。如果你正在对其执行每帧操作,则需要先检查数据是否已完全下载,如果没有,则不执行任何操作。
  • @Draco18s 是的,我知道但我该怎么做?
  • Check if the data exists first...嗯...if(textureDatas2.count &gt; 0)?

标签: c# unity3d ienumerator


【解决方案1】:

您可以在 Awake 方法的末尾添加一个名为 awakeFinished 的布尔字段,将其设置为 true。然后Update方法可以在做任何事情之前检查awakeFinished是否为真,如果为假则返回。

【讨论】:

  • 我怎样才能返回?
  • 我做到了,到目前为止效果很好,非常感谢。但我做的有点不同。我确实添加了 awakeFinished,如果不是,我只是在 update() 函数中创建了 this.start(),并且在 start() 的开头,我正在检查是否已经由 awakeFinished 启动。可能我做错了,我觉得我不应该在更新中调用 this.start() 但我不知道其他方式。有什么推荐的吗?
  • 我不太明白,但是你能不能把start的代码放在awake的末尾,然后完全删除start
【解决方案2】:

您可以在 Awake 方法的末尾创建一个行为类似于更新的协程,而不是使用更新。

IEnumerator Awake () {
    //...
    //Old Awake code goes here
    //...
    StartCoroutine(CheckForUpdates());
}


IEnumerator CheckForUpdates () {

     while(true) {
         //Put your Update code here instead
         yield return null;
     }

}

只要协程运行,while 循环就会每帧执行一次。

【讨论】:

  • 你能扩展一下吗?比如我该怎么做?而且,我已经用Update()编写了代码,如果我现在更改它们会不会有问题?
  • 希望我的编辑使它更容易理解。 CheckForUpdates 方法的作用类似于 Update(),您只需要手动启动它即可。
  • 我理解你的方式,当我在一个简单的项目中尝试它时,是的,它正在工作,谢谢你,因为我在 Update() 中连接了函数,当我尝试这个解决方案时它不能正常工作。你能有其他想法吗?
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
相关资源
最近更新 更多