- Home /
Healing Zone. 3D game
I have an area where my player would stand and gradually regain health, In this case Its Oxygen because the game is in space. I have my players health gradually decreasing over a time, and when it reaches a specified area the health would regenerate. But the Regeneration script I have automatically shoots it up to full health when I want to see a gradual increase. As well as once it hits full health its begins to decrease again despite still standing in the zone. the colliders notify me that it is hitting, but it doesn't work...
This is what I have
public class PlayerInfo : MonoBehaviour {
public float MaxOxyLv = 100;
public float CurrentOxyLv;
private const float coef = 2;
// private const float recoef = 10f;
public OxyLvl Oxygen;
void Start()
{
CurrentOxyLv = MaxOxyLv;
Oxygen.SetMaxOxy(MaxOxyLv);
Oxygen.SetOxy(CurrentOxyLv);
}
void Update()
{
CurrentOxyLv -= coef * Time.deltaTime;
Oxygen.SetOxy(CurrentOxyLv);
if (CurrentOxyLv <= 0f)
{
Suffocate();
}
if (CurrentOxyLv <= 20f)
{
print (" LOW OXYGEN WARNING!");
}
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Recover" && CurrentOxyLv < MaxOxyLv)
{
Debug.Log ("Refueling");
Refuel();
}
// if(CurrentOxyLv > 99)
// {
// DoNothing();
// }
}
void Refuel() { CurrentOxyLv+= 10 *Time.deltaTime; Oxygen.SetOxy(CurrentOxyLv);
}
// void DoNothing() // { // return; // } void Suffocate() { Debug.Log ("You Lose"); } } I've been working on this for hours....
Answer by Jaxcap · Dec 18, 2020 at 12:50 PM
OnTriggerEnter only gets called when the collision first happens, it doesn't keep getting called even if the thing stays inside. Instead, you could use OnTriggerEnter and OnTriggerExit to set a boolean that keeps track of whether your player is inside the refuel area, and then check the boolean in your Update function to see whether you should be gaining or losing fuel.
Something like this:
bool inRefuelArea;
void Update() {
if (inRefuelArea){
// Code that makes you regain health
} else {
// Code that makes you lose health
}
}
void OnTriggerEnter (Collider other){
if(other.gameObject.tag == "Recover") inRefuelArea = true;
}
void OnTriggerExit (Collider other){
if(other.gameObject.tag == "Recover") inRefuelArea = false;
}
Your answer
Follow this Question
Related Questions
Access to int from another script 1 Answer
How do I create an undertale player health bar in C #? 1 Answer
Fetching localized resources. 1 Answer