- Home /
Display text when energy reaches 0
I just tried each and everything I knew, but my program wont work. It shows the "You Lose" screen just when it decreases 1 NRG point. HELP!!!
var EnergyLoss = 1;
var EnergyLossTiming = 10;
var LastEnergyLossTime = 0;
var Energy = 100;
function Update(){
if((Time.time-LastEnergyLossTime)>EnergyLossTiming)
{
HealthConfidenceNRG();
LastEnergyLossTime = Time.time;
}
}
function HealthConfidenceNRG(){
Energy -= EnergyLoss;
if (Energy == -1);
{
Time.timeScale = 0;
LostTheGame = true;}
Debug.Log("Energy reduced to" + Energy);}
function OnGUI()
{
GUI.skin = newSkin;
GUI.Box (new Rect (0,1,100,30), "Energy" + ":" + Energy.ToString());
GUI.Box (new Rect (100,1,100,30), "Health" + ":" + Health.ToString());
GUI.Box (new Rect (200,1,100,30), "Confidence" + ":" + Confidence.ToString());
if (LostTheGame){
GUI.Box(Rect(Screen.width /2 - 100,Screen.height /2 - 100,250,200), "You Lose");
//Make Main Menu button
if(GUI.Button(Rect(Screen.width /2 - 100,Screen.height /2 - 50,250,50), "Main Menu")){
Application.LoadLevel(MenuSceneName);
}
//Make Retry button
if(GUI.Button(Rect(Screen.width /2 - 100,Screen.height /2 ,250,50), "Retry")){Application.LoadLevel(CurrentSceneName);}
}
}
Answer by robertbu · May 01, 2014 at 06:14 AM
One problem is on line 16:
if (Energy == -1);
The ';' at the end of the line terminates the 'if' statement. That means the rest of the code in this function will be executed the first time HealthConfidenceNRG() is called. Remove the ';' from the end of the line.
Answer by calmcarrots · May 01, 2014 at 06:39 AM
var LostTheGame = false; //Make sure you have this
var nextTimeUntilLoseEnergy = 0;
var energyLossInterval = 1; //Every one second, you will lose energy
var Energy = 100; // How much energy we have
var EnergyLoss = 1; //How much energy we will lose
function Update()
{
if(Time.time > nextTimeUntilLoseEnergy)
{
HealthConfidenceNRG();
nextTimeUntilLoseEnergy = Time.time + energyLossInterval; //From Time.time, add any value. Once Time.time passes this value, it will call 'HealthConfidenceNRG();'
} //This is more efficient since it uses less math
}
function HealthConfidenceNRG()
{
Energy -= EnergyLoss;
if (Energy <= -1) //No semicolon here. Also, make sure it is set to '<=' not to '=='
{
Time.timeScale = 0;
LostTheGame = true;
}
Debug.Log("Energy reduced to" + Energy);
}
Let me know if you don't understand a piece of the code. Just replace all your code (except for the OnGUI function) with my code.
Sorry, I know it works, but only removing the ";" worked like I wanted it.....sorry :(
However, I understand the code!
Sure! Everything helps and hopefully you learned something new
Your answer
Follow this Question
Related Questions
Energy refill script bug fix 2 Answers
Energy refill script bug fix 0 Answers
how to stop object before GO writes 1 Answer
Starting and stopping Coroutines 1 Answer
Breathing sound effect using timers 1 Answer