Выполнение кода 1 раз в полсекунды

Рейтинг: -4Ответов: 1Опубликовано: 15.07.2023

как я могу сделать так, чтобы мой счет увеличивался не так быстро, а каждые полсекунды -1 секунда?

вот мой код:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Control : MonoBehaviour
{
    public Text scoreText;
    public int score;
    public float time;
    private float timeStart;
    public float Second = 1f;
    void Update()
    {
        time -= Time.deltaTime;
        if (time <= 0)
        {
            ScoreManager.score += 1;

            time = timeStart;
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour
{
    [SerializeField] Text HighscoreText;
    [SerializeField] Text scoreText;
    public static float score;
    int highscore;
        void Start()
        {
            score = 0;
        }
        void Update()
        {
            highscore = (int)score;
            scoreText.text = "" + highscore.ToString();

            if (PlayerPrefs.GetInt("score") <= highscore)
            {
                PlayerPrefs.SetInt("score", highscore);
            }
            HighscoreText.text = "" + PlayerPrefs.GetInt("score").ToString();
        }

}

Ответы

▲ 0Принят

Для того чтобы что-то делать через определённый промежуток времени, есть корутины.

Ну и по замечаниям: не используйте статику, не используйте Update тогда, когда в этом нет необходимости, иначе ваша игра начнёт тормозить раньше, чем вы её допишете.

public class Control : MonoBehaviour
{
    public float interval; // интервал в секундах, полсекунды это 0.5f
    private ScoreManager manager;

    void Start()
    {
        manager = FindObjectOfType<ScoreManager>();
        // либо если оба скрипта на одном и том же объекте, то надо GetComponent<ScoreManager>()
        StartCoroutine(IncrementScore());
    }

    private IEnumerator IncrementScore()
    {
        while(true)
        {
            manager.Score++;
            yield return new WaitForSeconds(interval);
        }
    } 
}
public class ScoreManager : MonoBehaviour
{
    [SerializeField] private Text highscoreText;
    [SerializeField] private Text scoreText;

    private int _score;
    public int Score
    {
        get => _score;
        set
        {
            if (_score != value)
            {
                _score = value;
                UpdateScore(_score);
            }
        }
    }

    void Start()
    {
        int highscore = PlayerPrefs.GetInt("score", 0);
        highscoreText.text = highscore.ToString();
        scoreText.text = score.ToString();
    }

    private void UpdateScore(int score)
    {
        scoreText.text = score.ToString();
        int highscore = PlayerPrefs.GetInt("score", 0);
        if (score > highscore)
        {
            PlayerPrefs.SetInt("score", score);
            highscoreText.text = score.ToString();
        }
    }
}

Там где я использую get и set это в C# называется "свойство", почитайте что-нибудь про это.