- Home /
Update function doesn't work correctly
Hi there. I'm developing a simple game of zombie survival. This script is attached in an empty GameObject, which acts as the player's health.
#pragma strict
var health = 100;
var attack = 10;
var otherAttackDelay = 5;
function Attack1 () {
health -= attack;
Debug.log ("Under Attack 1!");
yield WaitForSeconds (otherAttackDelay);
Attack2 ();
}
function Attack2 () {
health -= attack;
Debug.log ("Under Attack 2!");
}
function Update () {
if (health == 80) {
Debug.log ("Die!");
}
}
The player has 100 health, and attack a zombie is 10. There are 5 second delay before the zombie attack again.
In the function Update I wrote a condition, if the player's health is equal to 80 (2 attacks) will display a Debug log with the message "Die!"
The problem is that when the zombie attacks only once (90 of life would there) immediately shows the "Die!". What am I doing wrong?
Greetings.
the problem is that your health is -= attack every frame you have to make var like this ..
var Attacked :boolean = false;
function Attack1 () {
if( attacked == false){
health -= attack;
}
attacked = true
Debug.log ("Under Attack 1!");
yield WaitForSeconds (otherAttackDelay);
attack = false;
Attack2 ();
}
If you call Attack1 multiple times from another script it could screw your system over. Also since Attack1 calls the Attack2 function which both takes 10 HP you are going to die. After your program is finished with Attack1 it will proceed to Attack2 because of the last line(11).
Answer by ticofa · Apr 14, 2015 at 11:22 PM
Hi :)! I'm not very familiar with java scripting, but i'd assume that its similiar to C# on the fact that, if you create costume functions, you will need to call them in the Update function :P
For example:
function Attack1 () {
if( attacked == false){
health -= attack;
}
attacked = true
Debug.log ("Under Attack 1!");
yield WaitForSeconds (otherAttackDelay);
attack = false;
Attack2 ();
}
function Update()
{
Attack1();
}
Hope it helps ;)!