- Home /
C# Reduce Health Over Time When Colliding With Object
Hi, I'm making a game where if you are in a specific radius of the enemy you will loose health over time. I am doing this by extending the range of the enemies collider with the 'Is Trigger' ticked. I have looked everywhere for a script that would work but none I have tried work for me. My question is: How might I be able to create this script?
If you need any more information do ask. Thanks, Joel.
using UnityEngine;
using System.Collections;
public class Player_Health : MonoBehaviour {
public static float curHealth = 100f;
public static float maxHealth = 100f;
public static float decHealth = 4f;
public static float regHealth = 2f;
void Start(){
curHealth = 98f;
}
void Update(){
if (curHealth < maxHealth) {
curHealth += regHealth * Time.deltaTime;
Debug.Log(curHealth);
}
}
void OnCollisionStay2D(Collision2D other){
if (other.gameObject.tag == "Darkness") {
curHealth -= decHealth * Time.deltaTime;
Debug.Log(curHealth);
}
}
}
Here is all the code I could come up with by myself. At the moment I do regenerate health when it's less than 100 but when I enter the collider my health does not go down. Please help.
================================================================================================= Okay I got it working! Here's the code to help anyone else with the same problem:
using UnityEngine;
using System.Collections;
public class Player_Health : MonoBehaviour {
public static float curHealth = 100f;
public static float maxHealth = 100f;
public static float decHealth = 6f;
public static float regHealth = 0.1f;
void Start(){
curHealth = 98f;
}
void Update(){
if (curHealth < maxHealth) {
curHealth += regHealth * Time.deltaTime;
Debug.Log(curHealth);
}
}
void OnTriggerStay2D(Collider2D other){
if (other.gameObject.tag == "Darkness") {
curHealth -= decHealth * Time.deltaTime;
Debug.Log(curHealth);
}
}
}
Your answer
Follow this Question
Related Questions
Unwanted jittery behavior 2 Answers
Colliders in a wall jut out 0 Answers
Trigger Spawning? 1 Answer
Detecting another object collision from another object script (2D) 0 Answers
OnTriggerEnter and GUIText problem 0 Answers