Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a timer to the code and then looping it

Trying to find a way to add a timer to my code and then continuously loop it with the timer. e.g Trying to craft items with a button click and then waiting 5 seconds for it to craft before it automatically begins to craft again and so on as long as I have the materials. Ive looked around on tutorials but havent been able to find what ive been looking for. This is the code I want to loop:

    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;
    }
}**
like image 264
CodingNewbie Avatar asked Sep 18 '26 17:09

CodingNewbie


1 Answers

This will completely solve your problem. You must place only one condition in 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 is a time-based function that can support wait times itself. While also returns the code as long as the condition is met. The combination of wait and `while causes the creator to create the item each time the condition is met and then wait 5 seconds. It rebuilds from where you still have the material.


For Example..

In the code below, with 2 irons, we can also make 2 swords. Just Run StartCoroutine when your character is going to the forge for e.g..

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..");
}

enter image description here

like image 81
KiynL Avatar answered Sep 20 '26 07:09

KiynL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!