How to increase Value of for example "gold" every second?

Hello, thank you for taking time for my question!

I want to create a small game that has a small simple economy. Every second, for example, the value ’ Gold ', which is represented as text, has to be increased by 1 every second.

I imagine this:

At the top left corner is ’ Gold: 15 ’

After that, the value ’ 15 ’ should be counted up every second.

Would anyone have a C# script for me please?

What you can do is have a timer that increments a gold value every second.

Script:

public int goldValue = 15;

private float timer = 0f;
public float delayAmount;

void Update()
{
   timer += Time.deltaTime;

   if (timer >= delayAmount)
   {
      timer = 0f;
      goldValue++;
   }
}

You can preset your custom delay amount e.g. 1.0f in the editor.

You can also use Coroutines, but I feel that this is a more efficient and simpler option.

using UnityEngine;
using UnityEngine.UI;

public class GoldManager : MonoBehaviour
{
	public int GoldValue = 15;
    public int Power = 5;
	public int DelayAmount = 1; // Second count
	public Text GoldValueText;
    public Text PowerText;

	protected float Timer;
	
	void Update()
	{
		Timer += Time.deltaTime;

		if (Timer >= DelayAmount)
		{
			Timer = 0f;
			GoldValue++; // For every DelayAmount or "second" it will add one to the GoldValue
			GoldValueText.text = "Gold value: " + GoldValue;
                    PowerText.text = "Power: " + Power;
		}
	}
}

By now you should get the main idea, giving code is not the best way to learn all the time but it’ll be enough for now :)!

The selected answer works, but I would much prefer a Coroutine in this situation, especially when you are dealing with time. Also great in terms of maintainability and readability.

    private int GoldValue = 15;
    private float TimeSeconds = 1;

    private void Start() {
        
        StartCoroutine(SpawnTimer());
    }

    private IEnumerator SpawnTimer() {
        
        while (true) {
            yield return new WaitForSeconds(TimeSeconds);
            GoldValue++;  
        }
    }