I could use a little help.
I've a state machine for an NPC that does a melee attack. The problem I'm running into is that the current code instantiates multiple instances when I only need one per cycle.
I could use some ideas.
This is the chunk of code I'm working with:
public void ChaseToAttack()
{
_navMeshAgent.speed = 3.5f;//slow down the navAgent
float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
//stop navMeshAgent to begin attack sequence
if (playerDistance <= stopAtDistance)
{
/// ensure enemy is always looking at player
enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);
if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player"))
{
_navMeshAgent.Stop();
currentState = _attackState;
//StartCoroutine(FistTimer());
PunchCycle();
}
/// ensure the enemy isn't hitting air & will always look for the player
else
{
transform.Rotate(chaseTarget.position, searchTurnSpeed * Time.deltaTime, 0);
}
/// end look & atttack player block
}
}
void PunchCycle()
{
StartCoroutine(AttackCycle());
}
void PunchClone()
{
clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
clone.transform.Translate(0,1f,0);
clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
}
IEnumerator AttackCycle()
{
//move animation here
AnimPunch();
PunchClone();
yield return new WaitForSeconds(4f);//fistTimer
BeAlert();
}
Thanks in advance...
EDIT:
Changed the code so it would only instantiate once- but now, it will only instantiate only once even though it's still in the attack sequence.
public void ChaseToAttack()
{
_navMeshAgent.speed = 3.5f;//slow down the navAgent
float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
//stop navMeshAgent to begin attack sequence
if (playerDistance <= stopAtDistance)
{
/// ensure enemy is always looking at player
enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);
if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player"))
{
_navMeshAgent.Stop();
currentState = _attackState;
StartCoroutine(AttackCycle());
}
/// ensure the enemy isn't hitting air & will always look for the player
else
{
transform.Rotate(chaseTarget.position, searchTurnSpeed * Time.deltaTime, 0);
}
/// end look & atttack player block
}
}
void PunchClone()
{
if(!didClone)
{
clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
clone.transform.Translate(0,1f,0);
clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
}
didClone = true;
}
IEnumerator AttackCycle()
{
//move animation here
AnimPunch();
yield return new WaitForSeconds(0.75f);//fistTimer
PunchClone();
}