在代码中加入定时器,然后循环

Adding a timer to the code and then looping it

试图找到一种方法在我的代码中添加一个计时器,然后用计时器不断地循环它。例如,尝试通过单击按钮来制作物品,然后等待 5 秒让它制作,然后它会自动开始再次制作等等,只要我有材料。我四处查看教程,但未能找到我一直在寻找的内容。这是我要循环的代码:

    public double copper;
public double copperBar;
public double copperBarValue;
public double multiplier;

public void Start()
{
    copperBar = 0;
    copperBarValue = 5;
    copper = 0;
    multiplier = 1;
}

    **public void FurnaceInteraction()
{
    if (copper >= copperBarValue)
    {
            copper -= copperBarValue;
            copperBar += 1 * multiplier;
    }
}**
public void Start()
{
    StartCoroutine(Timer());
}

IEnumerator Timer(){
    print("timer started and will wait 5 seconds");
    yield return new WaitForSeconds(5);
    print("timer finished after 5 seconds");
}

您可以像 Daniel 建议的那样使用 WaitForSeconds,或者您可以使用 Update 方法和 Time.deltaTime.

创建您自己的 Timer 方法

这是一个例子。

//tracks if we are looping or not
bool isLooping=false;

//holds the number of times left to loop
int loopTimes;

//holds the current time left
float timeLeft;

//wait 5 seconds
static float waitTime = 5;

private void Update()
{
    if (isLooping)
    {
        if (timeLeft>0)
        {
            timeLeft -= Time.deltaTime;
            RunFunctions();
        }
        else
        {
            loopTimes--;
            if (loopTimes > 0)
            {
                //print("loop again");
                timeLeft = waitTime;
            }
            else
            {
                //print("finished");
                isLooping = false;
            }
        }
    }
}

void RunFunctions() { }

public void StartLooping()
{
    //print("start looping");
    isLooping = true;
    loopTimes = 5;
    timeLeft = waitTime;
}

这将彻底解决您的问题。您必须在 while 中只放置一个条件。

private void Start() => StartCoroutine(Run());
public bool youHaveMaterials;
public IEnumerator Run()
{
    while (youHaveMaterials) // repeat time until your materials end
    {
        Debug.Log("Do Crafting..");
        yield return new WaitForSeconds(5);
    }
}

IEnumerator 是一个 time-based 函数,它本身可以支持等待时间。 While也returns代码只要满足条件即可。 wait 和 `while 的组合使创建者在每次满足条件时创建项目,然后等待 5 秒。它从你仍然拥有 material.

的地方重建

例如..

在下面的代码中,用2个铁杆,我们也可以做出2把剑。只是 运行 StartCoroutine 当你的角色要去锻造时

private void Start() => StartCoroutine(CraftSword());

public int Iron = 2;
public IEnumerator CraftSword()
{
    Debug.Log("Start Crafting..");
    while (Iron > 0)
    {
        Iron--;

        Debug.Log("Sword Created!!" + "Remaining Iron: " + Iron);

        if (Iron == 0) break;

        yield return new WaitForSeconds(.5f);
        
        Debug.Log("Wait 0.5 second.");
    }
    Debug.Log("My Irons End..");
}