Hi, i’m trying to make a simple script for a Space Invaders clone in Unity, i have this script where after the Player gets hitted by the enemy bullet he dies and the player get destroyed, after trhee seconds a new player will appear and loose a life. I got stuck because the variable IsAlive changes to false only on the frame where the Player gets hitted and then return to true, skipping all the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerLife : MonoBehaviour
{
public GameObject Player;
public int PlayerLifes = 3;
public float RespawnCooldown;
public Transform RespawnPoint;
public float time;
public int MaxLife = 3;
bool IsAlive=true;
void Start()
{
Player.GetComponent<GameObject>();
}
void Update()
{
if (!IsAlive) {
Destroy(Player);
time += Time.deltaTime;
LoseLifes(time,RespawnCooldown);
}
}
public void LoseLifes(float timer, float cooldown)
{
bool loselife = false;
Debug.Log(timer);
if (timer > cooldown&&!loselife)
{
GameObject.Instantiate(Player, RespawnPoint.position, transform.rotation);
loselife = true;
IsAlive = true;
}
if (PlayerLifes == 0 && !loselife)
{
GameOver();
}
if (loselife) {
PlayerLifes = PlayerLifes-1;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "EnemyBullet")
{
PlayerKilled();
}
}
void PlayerKilled()
{
IsAlive=false;
}
void GameOver()
{
Debug.Log("Game over");
}
}