Trying WaitForSeconds before Instantiating

So I’m making pong, and I’m trying to get it so that if the ball get’s destroyed, there’s like a half second before a new one gets instantiated so that the player can go from the bottom of the field to the middle.

here’s how I’m destroying:

//When this object enters a hitbox of object 'Col' enter this function
//If this object goes into either goal, destroy this object and increase the score for the opposing player
function OnTriggerEnter2D (col : Collider2D) {
	if(col.gameObject.name == "GoalRight") {
		Destroy (gameObject);
		gameMGMT.GetComponent(GameControlScript).LeftScore();
	}
	if(col.gameObject.name == "GoalLeft") {
		Destroy (gameObject);
		gameMGMT.GetComponent(GameControlScript).RightScore();
	}	
}

and this is how I’m instantiating

function Update () {
	if(GameObject.Find("Ball(Clone)") == null)
	{
		Instantiate(myBall, Vector3(0,0,0), Quaternion.identity);
	}

Now you can’t yield WaitForSeconds in an update, as it doesn’t allow Coroutines (don’t understand what that means). So I instead made a seperate function where it could yield and then instantiate. However when I tried that all that happened was it spawned a BUNCH of balls, like a stream that couldn’t be handled.

So does anyone have a way of handling this so that the game waits just half a second or so, before instantiating? and when that does happen, obviously only 1 ball is created.

Cheers

@bearzerk

Update is called many times per second so if you are calling the function from update, it would be called as many times as update will be called and due to that you have a stream of balls instantiated.

Try keeping a bool, something like this

public bool IsBallDestroyed;

void Update()
{
	if(IsBallDestroyed)
	{
		IsBallDestroyed = false;
		StartCoroutine(_Insta_the_ball());
	}
}

IEnumerator _Insta_the_ball()
{
	yield return new WaitForSeconds(1f);

	// Instantiate the ball
}

make the boolean true in OnTriggerEnter2D.

Sorry I work on c#, hope you will be able to convert it to unity script.

I actually found a solution last night. Since I’m calling a coroutine, calling it from a dying object doesn’t work as the coroutine stops as the object gets destroyed. So now I call a ‘caller’ function which in turn then performs teh coroutine and that works perfectly fine :slight_smile:

Cheers though