We will now add a lives-counter for the ball, every time the ball spawns after falling it substracts a life. When the lives are zero the scene will change to the End Game scene.
Copy the following code for the Ball script and save the file:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class Ball : MonoBehaviour
{
private bool jumpKeywaspressed = false;
private int space_press_count = 0;
private float horizontal_Input;
private Rigidbody rigidbody_component;
[SerializeField] private Transform ground_check;
[SerializeField] private Transform SpawnPoint;
public GameObject level1;
public int platformcounter = 0;
public int life = 3; //define the max number of lives
public bool flag = true;
// Start is called before the first frame update
void Start()
{
rigidbody_component = GetComponent<Rigidbody>();
level1 = GameObject.Find("Level 1");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jumpKeywaspressed = true;
}
horizontal_Input = Input.GetAxis("Horizontal");
if (GetComponent<Transform>().position.y < (level1.GetComponent<Transform>().position.y - 3.0f))
{
GetComponent<Transform>().position = SpawnPoint.transform.position;
//when all three lives are over the scene change to gameover screen
if (life > 1)
{
life = life - 1;
flag = true; //flag is true so that when the ball respawn it has 3 jump in mid-air
}
else
{
SceneManager.LoadScene(2);
}
}
}
private void FixedUpdate()
{
rigidbody_component.velocity = new Vector3(3 * horizontal_Input, rigidbody_component.velocity.y, 0);
if (Physics.OverlapSphere(ground_check.position, 0.1f).Length == 1)
{
if (flag == true)
{
if (jumpKeywaspressed && space_press_count < 3 && rigidbody_component.velocity.y < 0)
{
rigidbody_component.AddForce(Vector3.up * 8, ForceMode.VelocityChange);
jumpKeywaspressed = false;
space_press_count = space_press_count + 1;
}
if (jumpKeywaspressed && space_press_count < 3 && rigidbody_component.velocity.y > 0)
{
rigidbody_component.AddForce(Vector3.up * 6, ForceMode.VelocityChange);
jumpKeywaspressed = false;
space_press_count = space_press_count + 1;
}
jumpKeywaspressed = false;
}
else
{
if (jumpKeywaspressed && space_press_count < 2 && rigidbody_component.velocity.y < 0)
{
rigidbody_component.AddForce(Vector3.up * 8, ForceMode.VelocityChange);
jumpKeywaspressed = false;
space_press_count = space_press_count + 1;
}
if (jumpKeywaspressed && space_press_count < 2 && rigidbody_component.velocity.y > 0)
{
rigidbody_component.AddForce(Vector3.up * 6, ForceMode.VelocityChange);
jumpKeywaspressed = false;
space_press_count = space_press_count + 1;
}
jumpKeywaspressed = false;
}
}
else
{
space_press_count = 0;
if (jumpKeywaspressed)
{
flag = false;
rigidbody_component.AddForce(Vector3.up * 6, ForceMode.VelocityChange);
jumpKeywaspressed = false;
}
}
}
}