- Home /
Kill script on collision when lives are lost
Hi, I just started studying Unity at TAFE and need help, I have a player that has 5 lives in a 2D game... and I have a ground with a kill script in it which on collision reduces the players life by 5 therefore killing the player, however if the player does not have exactly 5 lives left it won't die on collision, and I cannot for life of me work out what it is i need to do to make my character with lives of 1, 2, 3 or 4 left to get them to activate the collision, here is the code, do i need an array not sure how to implement it ..
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GroundKill : MonoBehaviour {
void OnCollisionEnter2D(Collision2D col)
{
GameControlScript.health -= 5;
}
}
Answer by $$anonymous$$ · Oct 20, 2018 at 01:41 PM
Before someone can Answer this for sure, he/she also needs to see the Script where the Number of current player Lives is stored. Because I can't see this Script anywhere in this Question, I must assume what you could've done wrong.
I assume, that in the GameControlScript is a Update()
Method, and Part of this Update()
Method says something along the Lines of:
Update()
{
if (health = 0)
{
//Kill Code goes here
}
}
But you should Replace the =
from if (health = 0)
with a =<
.
if (health = 0) //If Health is equal 0
only Cares, if health is exactly 0. It doesn't Care, if it's higher or lower than 0, but when it's if (health =< 0) //If Health is equal or less than 0
, this Part of the Code also does it's Commands, if the Player has less than 0 health.
Whenever you're dealing with Health in Programming, please Keep in Mind, that the Health (or any Numerical Variable) can Sink below 0, so you need to Build the Code in a Way, that accounts for it.
Again, I could not answer this for sure because of Missing Information, but this eventually happens anyone, and I hope I was able to help you with this Answer.