Top Andrey
Знаток
(394)
1 месяц назад
Для перезапуска сцены, когда таймер завершится, необходимо использовать класс `SceneManager` из пространства имен `UnityEngine.SceneManagement`. Также нужно добавить соответствующую логику в метод `Update`.
Вот модифицированный код с добавлением перезапуска сцены:
```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement; // Необходимо для управления сценами
public class SimpleTimer : MonoBehaviour
{
[SerializeField] private float time;
[SerializeField] private Text timerText;
private float _timeLeft = 0f;
private bool _timerOn = false;
private void Start()
{
_timeLeft = time;
_timerOn = true;
}
private void Update()
{
if (_timerOn)
{
if (_timeLeft > 0)
{
_timeLeft -= Time.deltaTime;
UpdateTimeText();
}
else
{
_timerOn = false;
ReloadScene(); // Перезапуск сцены
}
}
}
private void UpdateTimeText()
{
if (_timeLeft < 0)
_timeLeft = 0;
float minutes = Mathf.FloorToInt(_timeLeft / 60);
float seconds = Mathf.FloorToInt(_timeLeft % 60);
timerText.text = string.Format("{0:00} : {1:00}", minutes, seconds);
}
private void ReloadScene()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
```
В этом коде добавлена функция `ReloadScene`, которая вызывает метод `SceneManager.LoadScene`, перезагружающий текущую сцену. Эта функция вызывается, когда время на таймере достигает нуля.
using UnityEngine;
using UnityEngine.UI;
public class SimpleTimer: MonoBehaviour
{
[SerializeField] private float time;
[SerializeField] private Text timerText;
private float _timeLeft = 0f;
private bool _timerOn = false;
private void Start()
{
_timeLeft = time;
_timerOn = true;
}
private void Update()
{
if (_timerOn)
{
if (_timeLeft > 0)
{
_timeLeft -= Time.deltaTime;
UpdateTimeText();
} else
{
_timeLeft = time;
_timerOn = false;
}
}
}
private void UpdateTimeText()
{
if (_timeLeft < 0)
_timeLeft = 0;
float minutes = Mathf.FloorToInt(_timeLeft / 60);
float seconds = Mathf.FloorToInt(_timeLeft % 60);
timerText.text = string.Format("{0:00} : {1:00}", minutes, seconds);
}
}