- Home /
Trouble with lives
I having an issue where when my player hit an enemy he dies as he should, but sometimes he loses 2 lives and others he only loses 1. I think the issue might be that my character has two colliders: a circle collider2D and a box Collider2D and they are both hitting the enemy. I have no idea how to fix it though. Here are my scripts (They are both attached to my player)
Lives:
using UnityEngine;
using System.Collections;
public class Lives : MonoBehaviour {
public static int PlayerLives = 5;
public int MaxLives = 999;
public GUISkin Life;
public Rect LifeDisplay;
void Update ()
{
if(PlayerLives >= MaxLives)
{
PlayerLives = MaxLives;
}
if(PlayerLives <= 0)
{
Application.LoadLevel(0); //Gameover Level
}
PlayerPrefs.SetInt("Lives", PlayerLives);
PlayerLives = PlayerPrefs.GetInt("Lives");
}
void OnGUI()
{
GUI.skin = Life;
GUI.Label(LifeDisplay, "Lives: " + PlayerLives.ToString(), GUI.skin.GetStyle("Lives"));
}
}
Enemy:
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public string Level = "";
void OnTriggerEnter2D(Collider2D enemy)
{
if(enemy.tag == "Enemy")
{
Lives.PlayerLives--;
Application.LoadLevel(Level);
}
}
}
Any help would be much appreciated.
Answer by rutter · Aug 09, 2014 at 02:52 AM
Sounds like you need your player to become invulnerable for a short period of time after they're hit.
For example:
//keep track of next time we can be hurt
float nextVulnerableTime = 0f;
//after being hit, we'll be invulnerable for this many seconds
float invulnSeconds = 5f;
void TakeDamage() {
if (Time.time > nextVulnerableTime) {
nextVulnerableTime = Time.time + invulnTime;
//subtract life or whatever needs to be done
}
}
As an alternative, you could make sure to always distinguish which collider you hit, and make sure that an enemy is disabled after it hits one of them.
Thanks! that fixed it. I would upvote your answer but I dont have 15 rep yet.
this makes sense but what do you turn off on the player so they cant get hit for that time period? The collider?