-1

I have a very simple game, I wanted to add a score to it, after that it started to lag a lot, here is my score counter code, I think the problem is in it

using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour
{
    public Text scoreText;
    public int scr = 0;
    
    void Update(){
       System.Threading.Thread.Sleep(1000);
       scr = scr + 1;
       scoreText.text = scr.ToString(); 
    }
}
Ilya
  • 254
  • 2
  • 11

2 Answers2

1

If you want to execute Update() method each 1000ms, maybe better aproach is to create coroutine executing each 1000ms.

void Start(){
       StartCoroutine(SampleCoroutine());
}

IEnumerator SampleCoroutine()
{
       while(true){
            yield return new WaitForSeconds(1);
            scr = scr + 1;
            scoreText.text = scr.ToString();
       }
}
1

Update is called every frame if i remember correctly.
So what you are doing is every frame pausing the game for a second

try this no way the best solution but it may be a start

public class Score : MonoBehaviour
{
    public Text scoreText;
    public DateTime starttime

    void Start()
    {
       starttime = DateTime.Now;
    }
    void Update()
    {
        scoreText.text = ((int)(DateTime.Now - starttime).TotalSeconds).ToString(); 
    }
}
Connor Stoop
  • 1,574
  • 1
  • 12
  • 26