# Delaying the game to restarts with Coroutine

I want to create some sort of delay for the game to restarts when the ball is stops moving but the game keeps restarting whenever the velocity reaches zero. I want use a timer where the game will restarts when the ball is stopping for too long but I don't know how. Here's the code. The Restart() will be called from another script when the game starts and the ball will starts moving. Any help would be appreciated.

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class BallCondition : MonoBehaviour {

// Use this for initialization
public bool isLose = false;
public Rigidbody2D rb;

void Awake () {

rb = GetComponent<Rigidbody2D>();
}
public IEnumerator Restart()
{
Debug.Log(rb.velocity);
if((rb.velocity.x)==0 && (rb.velocity.y) == 0)
{
//print(Time.time);
Debug.Log("stopped");
if((rb.velocity.x)==0 && (rb.velocity.y) == 0 && !isLose)
{
yield return new WaitForSeconds(3);
Debug.Log("lose");
isLose = true;
}
}
}
}


This is the script where I call the Restart()

using UnityEngine;
using System.Collections;

public class Force : MonoBehaviour {

public float moveSpeed = 5;
public static bool isAlreadyClicked = false;

void Start()
{
Reset();
}

void Update()
{
if(Input.GetMouseButton(1))
{

{
Debug.Log("clicked");
BallCondition player = GetComponent<BallCondition>();
StartCoroutine(player.Restart());
}
}

}
public void Reset()
{
}
}

• It would help to see the script where you're calling Restart. – DMGregory Oct 21 '16 at 3:39
• Edited the question, sorry about that. Hope it helps – user3132527 Oct 21 '16 at 3:44
• Can you provide the Debug.Log result for further clarification? – Geo Baby Oct 21 '16 at 10:35

Your code for Restart will only run once.

You could use something like:

public IEnumerator Restart()
{
while (true)
{
Debug.Log("stopped");
// if you want to limit the check by 1 per second
yield return new WaitForSeconds(1f);
if (rb.IsSleeping())
{
yield return new WaitForSeconds(3);
Debug.Log("lose");

I've also changed the velocity check for rb.IsSleeping() (more info in Unity Docs)