- Home /
Lose life on level restart
Hello,
I'm having a hard time with my code below. What I need is on the Character death, the level restarts (works perfectly) and the character loses a life (the part I'm having issues with)
I have a code that the character loses life but it starts losing life continuously on play rather than losing only 1 life on death and restarting the level. I think it's because I have it in the Update method but I also tried doing that in the pDeath method and then it continuously lost life after the level restarted. Below is the code I have written, any help you all can provide would be greatly appreciated.
static public Player S;
public float speed = 30;
public float rollMult = -45;
public float pitchMult = 30;
public float life = 3;
public float GameOverDelay = 1f;
private Scene scene;
public bool shipAlive; //instead of destroying the object completely, just keep a bool and disable object if true. Faster and will not break dependency.
private bool levelRestart;
public GameObject playerExplosion;
public Transform shotSpawn;
public GameObject shot;
private float nextFire;
public float fireRate;
//Ship status information
[SerializeField]
private void Awake()
{
if (S != null)
{
Destroy(this.gameObject);
}
S = this; //Sets the player
shipAlive = true;
levelRestart = false;
}
private void Update()
{
Fire();
scene = SceneManager.GetActiveScene();
if (levelRestart == true)
{
life = life - 1;
levelRestart = false;
}
}
private void FixedUpdate()
{
if (!shipAlive)
return;
float xAxis = Input.GetAxis("Horizontal");
float yAxis = 0;
Vector3 pos = transform.position;
pos.x += xAxis * speed * Time.deltaTime;
pos.y += yAxis * speed * Time.deltaTime;
transform.position = pos;
transform.rotation = Quaternion.Euler(yAxis * pitchMult, 0, xAxis * rollMult);
}
void Fire()
{
if(Input.GetButton("Jump") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Boundary")
{
StartCoroutine(goDelay());
pDeath();
}
}
void pDeath()
{
Destroy(this.gameObject);
Application.LoadLevel(scene.name);
levelRestart = true;
}
public IEnumerator goDelay()
{
yield return new WaitForSeconds(GameOverDelay);
}
void GameOver()
{
if (life >= 0)
{
SceneManager.LoadScene("GameOver");
}
}
Follow this Question
Related Questions
Lose life on level restart 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Character Rotation 2 Answers