The game restarts after completion, but upon restarting, it unexpectedly exits after a few seconds. What steps should I take to debug this issue? Is there a need to change in the Unity editor?
I want this game in Unity to restart with a delay of 4 seconds after its completion properly.
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using TMPro;
public class BallController : MonoBehaviour
{
private float collisionTime = 0f;
private bool timerActive = true;
public float collisionThreshold = 5f;
public float restartDelay = 4f;
public TextMeshProUGUI timerText;
public GameObject cylinderPrefab;
private GameObject cylinderObject;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("CylinderTag"))
{
collisionTime = Time.time;
timerActive = true;
cylinderObject = collision.gameObject;
}
else if (collision.gameObject.CompareTag("Ground"))
{
timerActive = false;
UpdateTimerText();
}
}
void Update()
{
if (timerActive && Time.time - collisionTime > collisionThreshold)
{
if (cylinderObject != null)
{
Destroy(cylinderObject);
}
StartCoroutine(RestartGameAfterDelay(restartDelay));
}
UpdateTimerText();
}
IEnumerator RestartGameAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
void UpdateTimerText()
{
if (timerText != null)
{
float remainingTime = Mathf.Max(0f, collisionThreshold - (Time.time - collisionTime));
if (timerActive)
{
timerText.text = $"Time: {remainingTime:F1}s";
}
else
{
timerText.text = "";
}
}
}
}