用于堆叠时间的循环(C#,Unity)

时间:2015-06-04 10:06:33

标签: c# unityscript

我希望将时间计算为10秒,然后使countToTen = 0并再次开始循环,直到它再次达到10。现在,Unity正在粉碎,我不知道为什么。

你能帮助我吗?

public float countToTen;    
void Update(){
       do{
            if(countToTen<=10){
               countToTen=(int)(Time.time%60f);
            }
        }
        while(countToTen<=10);}

3 个答案:

答案 0 :(得分:0)

这不是正确的做法。我的意思是,你可以这样做但是当你有一个雪橇时你会使用凿子。

IEnumerator myFunction( float s )
{
    Debug.log ("waiting...");
    yield return new waitForSeconds(s);
    Debug.log("tada!");
}

//call me on onclick or whenever, but not in update() ^^
void startFunction() 
{
    StartCoroutine(myFunction( 10));
}

void update()
{

}

答案 1 :(得分:0)

该循环将阻止更新,因为时间不会改变,直到更新功能完成执行。相反,我猜你想要做的是数到10秒,然后再做一些事情,然后再等10秒钟。

Unity的做法是使用co-routine。基本上,你做的事情如下:

IEnumerator WaitThenDoSomething(float WaitTime) {
    while(running) 
    {
        yield return new WaitForSeconds(WaitTime);
        DoSomething();
    }
}

其中DoSomething()是一个每隔10秒执行一次的函数,直到running设置为false。您可以使用Start()方法中的以下代码开始此操作:

StartCoroutine(WaitThenDoSomething(10.0));

答案 2 :(得分:0)

就是这样,完美地运作。谢谢你们帮助我。

using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
using System.Collections.Generic;

public class TextReadFromFile : MonoBehaviour {

    GameObject player;
    public TextAsset wordFile;                                // Text file (assigned from Editor)
    private List<string> lineList = new List<string>();        // List to hold all the lines read from the text file
    Text text;
    Timer timer;
    PlayerHealth playerHealth;

    void Awake ()
    {
        player = GameObject.FindGameObjectWithTag ("Player");
        playerHealth = player.GetComponent <PlayerHealth>();
        text = GetComponent <Text>();
    }
    void Start()
    {
        ReadWordList();
        Debug.Log("Random line from list: " + GetRandomLine());

        StartCoroutine (Count(2.0f));

        }

    public void ReadWordList()
    {
        // Check if file exists before reading
        if (wordFile)
        {
            string line;
            StringReader textStream = new StringReader(wordFile.text);

            while((line = textStream.ReadLine()) != null)
            {
                // Read each line from text file and add into list
                lineList.Add(line);
            }

            textStream.Close();
        }
    }

    public string GetRandomLine()
    {
        // Returns random line from list
        return lineList[Random.Range(0, lineList.Count)];
    }

    IEnumerator Count(float WaitTime){

        while(playerHealth.currentHealth >= 0)
        {
            yield return new WaitForSeconds(WaitTime);
            text.text = GetRandomLine();
        }
}


}