Hi I’m trying to Instantiate a new ball into my scene so that when the player dies, he loses 1 life and the ball comes back to the paddle. Much like re-loading the scene except keeping the already broken bricks broken so the player doesn’t have to break them over again.
So far I have destroyed the old ball and instantiated a new one at a set position, but I don’t know how to reattached it to the paddle. When I Instantiate the new ball, it just floats at the position where I instantiated instead of attaching to or moving with the paddle, which I seems like it should be done during update in Ball. The ball does launch on click, so I’m doing something right at least.
Here’s the code I’ve added to GameSesssion:
public int LoseALife()
{
lives--;
lifeText.text = lives.ToString();
ResetBall();
return lives;
}
private void ResetBall()
{
Ball oldBall = FindObjectOfType<Ball>();
oldBall.DestroyBall();
Instantiate(newBall, new Vector3(5, 1.25f, 3), transform.rotation);
Ball ball = FindObjectOfType<Ball>();
ball.ResetPosition();
And what I’ve added to Ball (plus Update and LockBallToPaddle, for reference):
void Update()
{
if (!hasStarted)
{
LockBallToPaddle();
LaunchOnMouseClick();
}
}
private void LockBallToPaddle()
{
Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
transform.position = paddlePos + paddleToBallVector;
}
public void ResetPosition()
{
hasStarted = false;
print ("Resetting");
paddleToBallVector = transform.position - paddle1.transform.position;
}
public void DestroyBall()
{
Destroy(gameObject);
}
I’m also wondering if using Ball oldBall = FindObjectOfType(); is the best way to find the ball. If I were to add extra balls at once, is there an easy way to find which ball is triggering the Lose Collider, or would I need to do something like FindObjectsOfType(); and search through all balls to find which has a y position <0?
Thanks you.