I’m really new to coding so please keep the answers simple if you can (Should be easy to answer I couldn’t find much online).
I want to update/increase the score every second and not every frame, I’ve tried some Time.deltatime stuff but it hasn’t worked
using UnityEngine;
public class GameManager : MonoBehaviour
{
public int score;
private PlayerController playerControllerScript;
// Start is called before the first frame update
void Start()
{
playerControllerScript = GameObject.Find("Player").GetComponent<PlayerController>();
score = 0;
}
// Update is called once per frame
void Update()
{
if (!playerControllerScript.gameOver)
{
if (playerControllerScript.doubleSpeed)
{
score += 2;
}
else
{
score++;
}
Debug.Log("Score: " + score);
}
}
}
The easiest way you could do this is by creating an IEnumerator that waits one second and then loops.
private void Start()
{
StartCoroutine(count());
}
private IEnumerator count()
{
yield return new WaitForSeconds(1f);
if (!playerControllerScript.gameOver)
{
if (playerControllerScript.doubleSpeed)
{
score += 2;
}
else
{
score++;
}
Debug.Log("Score: " + score);
}
StartCoroutine(count());
}
You have to put StartCoroutine(count());
in Start()
, that’s necesary. Hope this helps
1 Like
The easiest thing is to use InvokeRepeating
not Coroutine
as some of the beginners could not understand coroutine properly. Anyway both solutions should be okay 
Of note, using yield return new WaitForSeconds(1f);
in a Coroutine will wait for a *MINIMUM* of 1 second, until the first frame after 1 second has elapsed.
It would be more sensible (for a continuous score) to keep a rolling counter as a float/double/etc. and increment the score whenever it exceeds 1:
float scoreCounter;
int score;
void Update()
{
scoreCounter += Time.deltaTime;
while(scoreCounter >= 1f)
{
// https://learn.unity.com/tutorial/ternary-operator
score += playerControllerScript.doubleSpeed ? 2 : 1;
scoreCounter -= 1f;
}
}
1 Like
I agree with this, but you should also consider resseting scoreCounter to 0, why?: Time.DeltaTime can sometimes exceed 1, and be a value of 1.20, so if you just do -= 1f, sometimes the score is going to update faster. But yeah, this is a really valid solution.
It doesn’t make sense to reset the scoreCounter to zero, for the same reason that I offered my suggestion in the first place. When the frame hits, anything above exactly 1.0 is discarded. Let’s say one frame hits at 0.99 seconds and the next at 1.2 seconds. Repeat that 5 times and you’ve lost an entire second of increment, for a score of 5 after 6 seconds.
If a single frame takes a long time, you need to account for it having taken that long, and accumulate any and all seconds added on during that time. (Mind you, if the process were actually complex to calculate, then you would want safeguards to avoid exponential calculation cost growth as processing the while() loop starts taking longer than its own frame)