There is a big bug in this script in Unity that I wanted to ask before changing the functions, is there an easier way to fix this bug? It is a simple game that if the ball hits the cylinder in the middle of the field for 5 seconds, the first cylinder will come down and the player will win. The bug is that if the ball hits the cylinder in a very short time and returns very quickly, the ground will not notice and the timer will continue and after 5 seconds the cylinder will come down and win.
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Cylinder"))
{
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)
{
restarting = true;
if (cylinderObject != null)
{
Vector3 newPosition = cylinderObject.transform.position;
newPosition.y -= 2f;
cylinderObject.transform.position = newPosition;
timerActive = false;
}
StartCoroutine(RestartGameAfterDelay(restartDelay));
}
UpdateTimerText();
}
IEnumerator RestartGameAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
void UpdateTimerText()
{
if (restarting)
{
timerText.text = "";
return;
}
if (timerText != null)
{
float remainingTime = Mathf.Max(0f, collisionThreshold - (Time.time - collisionTime));
if (timerActive)
{
timerText.text = $"Time: {remainingTime:F1}s";
}
else
{
timerText.text = "";
}
}
}
}