Hi all, I am coding a pong game. The code below shows that it is supposed to respawn after waiting for 1 second, however after adding the yield return new Waitforseconds, for some reason it does not respawn! If I comment that line out, the ball respawns just fine. Does anyone know why?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnScore : MonoBehaviour
{
private int player1score;
private int player2score;
private Rigidbody2D rb;
public BallMovement ballMovement;
private void Start()
{
player1score = 0;
player2score = 0;
rb = GetComponent<Rigidbody2D>();
ballMovement = GetComponent<BallMovement>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "WallLeft")
{
player1score += 1;
Debug.Log("Player1:" + player1score);
StartCoroutine(ResetBallPosition());
}
if (collision.gameObject.name == "WallRight")
{
player2score += 1;
Debug.Log("Player2:" + player2score);
StartCoroutine(ResetBallPosition());
}
}
IEnumerator ResetBallPosition()
{
gameObject.SetActive(false);
gameObject.transform.position = Vector3.zero;
yield return new WaitForSeconds(1f); // the ball respawns at the centre if I delete this line, but after adding it it does not seem to work!
gameObject.SetActive(true);
rb.velocity = Vector2.right * ballMovement.speed;
yield return null;
}
}