When it repeats the function, it doesn’t do the Yield, but if I go out of the range and go back into the range (See code for what I mean) it will do the yield, but if I stay in the range it just keep going and going without a pause.
function Update () {
//Follow function
var playerPos = player.transform.position;
dist = Vector3.Distance(playerPos,transform.position);
if (dist > 1.0 && attack == false) {
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, Time.deltaTime*speed);
}
else {
attack = true;
if (attack == true) {
attackPlayer();
}
}
}
function attackPlayer() {
yield WaitForSeconds(1.2);
if( dist < 1.0 ) {
var pStats = player.GetComponent(playerStats);
pStats.pLife -= baseDamage;
pLife = pStats.pLife;
}
attack = false;
}
If you want to respect an interval of 1.2s between attacks, the logic is wrong. WaitForSeconds only stops coroutines, not Update - you should use the boolean attack in a different manner in order to inhibit attacks while the coroutine is running:
function Update(){
if (dist > 1.0) { // out of attack range: chase player
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, Time.deltaTime*speed);
}
else // inside range: attack!
if (attack == false){ // but only if interval ended
attackPlayer();
}
}
function attackPlayer() {
attack = true; // attacking now - don't call attackPlayer!
var pStats = player.GetComponent(playerStats);
pStats.pLife -= baseDamage; // apply damage
pLife = pStats.pLife;
yield WaitForSeconds(1.2); // wait interval
attack = false; // interval ended: can attack again
}
In such a case it’s way easier to use just a coroutine without Update:
function Start()
{
var pStats = player.GetComponent(playerStats);
while(true)
{
var playerPos = player.transform.position;
if (Vector3.Distance(playerPos,transform.position) < 1.0)
{
yield WaitForSeconds(1.2);
while(Vector3.Distance(playerPos,transform.position) < 1.0)
{
pStats.pLife -= baseDamage;
pLife = pStats.pLife;
yield WaitForSeconds(1.2);
}
]
else
{
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, Time.deltaTime*speed);
yield;
}
}
}
Just make sure you always yield each iteration or it will crash your game