Hello, I am making a game where you shoot balls to a target. I used OnBecameInvisible to know when i missed the shot so it changes to the game over screen, but it also works when i do hit the target, as collision destroys the ball and spawns a clone. How can I fix this?
Here is my code:
public class BallShooter : MonoBehaviour
{
// Variables
Rigidbody rb;
public GameObject Ball;
public Transform spawnPoint;
float holdstartTime = 0f;
public float speed = 500;
private bool onGround = false;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float delta = Time.time - holdstartTime;
float adjustedSpeed = speed * delta;
if (Input.GetKeyDown(KeyCode.Space))
{
holdstartTime = Time.time;
}
if (Input.GetKeyUp(KeyCode.Space) && onGround)
{
rb.AddForce(Vector3.forward * adjustedSpeed);
rb.AddForce(Vector3.up * adjustedSpeed);
onGround = false;
}
}
// What happens when ball collides
private void OnCollisionEnter(Collision collision)
{
// If collision is with Wall
if(collision.gameObject.tag == "Wall")
{
Destroy(gameObject, 0.2f);
SpawnBall();
GetComponent<Renderer>().material.color = Color.black;
}
// If collision is with floor
if (collision.gameObject.tag == "Floor")
{
onGround = true;
}
}
// Spawn function
void SpawnBall()
{
Instantiate(Ball, spawnPoint.position, Quaternion.identity);
}
private void OnBecameInvisible()
{
GameFinished();
}
public void GameFinished()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}