So very quickly, I know many will say to use "OnBecomeInvisible()" but that doesn't work in this case.
I'm making pong, and as a fail safe for the ball potentially escaping the play area, I want to destroy the ball and then spawn in a new one in it's place. OnBecomeInvisible doesn't work because as soon as I destroy the ball, I call a coroutine which waits half a second and spawns in a ball. If OnBecomeInvisible is also running, whenever a ball is scored, 4 take it's place!
Here's some of the code:
1st the ballscript itself
function OnTriggerEnter2D (col : Collider2D) {
if(col.gameObject.name == "GoalRight") {
gameMGMT.GetComponent(GameControlScript).LeftScore();
gameMGMT.GetComponent(GameControlScript).SpawnBallCall();
Destroy (gameObject);
}
if(col.gameObject.name == "GoalLeft") {
gameMGMT.GetComponent(GameControlScript).RightScore();
gameMGMT.GetComponent(GameControlScript).SpawnBallCall();
Destroy (gameObject);
}
}
//When outside of the scene camera, destroy this object (fixes issue if the ball falls out of play)
function OnBecameInvisible() {
gameMGMT.GetComponent(GameControlScript).SpawnBallCall();
Destroy(gameObject);
}
So, in order to yield I need to do a secondary call to a function in the gamemanager script:
function SpawnBallCall() {
SpawnBall();
}
function SpawnBall() {
yield WaitForSeconds (0.5);
Instantiate(myBall, Vector3(0,0,0), Quaternion.identity);
}
Like I say, using OnBecomeInvisible only serves to spawn 3-5 new pong balls instead of the singular 1 I want. So can anyone think of other work arounds?
↧