Book Image

Mastering Unity Scripting

By : Alan Thorn
Book Image

Mastering Unity Scripting

By: Alan Thorn

Overview of this book

Table of Contents (17 chapters)
Mastering Unity Scripting
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating the Attack state


In the Attack state, the enemy continually attacks the player as long as they're visible. After an attack, the enemy must recover before launching a new attack. The only exit condition for this state is losing sight of the player. When this happens, the enemy returns to the Chase state and, from there, they either go back to the attack state or into Idle, depending on whether the player has been found, as shown in the following code sample 7-10:

//This coroutine runs when object is in attack state
 public IEnumerator State_Attack()
 {
    //Set current state
    CurrentState = AI_ENEMY_STATE.ATTACK;
 
    //Set Chase State
    ThisAnimator.SetTrigger((int) AI_ENEMY_STATE.ATTACK);
     //Stop nav mesh agent movement
    ThisAgent.Stop();
 
    //Set up timer for attack interval
    float ElapsedTime = 0f;
 
    //Loop forever while in attack state
    while(CurrentState == AI_ENEMY_STATE.ATTACK)
    {
         //Update timer
         ElapsedTime += Time.deltaTime...