Hello! I have a script that lets enemy chase the player and setted up an Animator for this enemy with different parameters (isIdle, isMoving and isAttacking). And now I am trying to make enemy stop moving and rotating when isAttacking state is active. Here is the script I have:
using System.Collections;
using UnityEngine;
public class Chase : MonoBehaviour {
public Transform player;
static Animator anim;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update ()
{
if (Vector3.Distance (player.position, this.transform.position) < 3)
{
Vector3 direction = player.position - this.transform.position;
direction.y = 0;
this.transform.rotation = Quaternion.Slerp (this.transform.rotation, Quaternion.LookRotation (direction), 0.1f);
anim.SetBool ("isIdle", false);
if (direction.magnitude > 1)
{
this.transform.Translate (0, 0, 0.05f);
anim.SetBool ("isWalking", true);
anim.SetBool ("isAttacking", false);
}
else
{
anim.SetBool ("isAttacking", true);
anim.SetBool ("isWalking", false);
//StartCoroutine(StopMovement(5.0f));
}
}
else
{
anim.SetBool ("isIdle", true);
anim.SetBool ("isWalking", false);
anim.SetBool ("isAttacking", false);
}
}
}
Firstly I tried to apply this guy’s method (How To Stop Enemy Movement During Its Attack Animation - Questions & Answers - Unity Discussions), when you assign StopMovement function on every animation clip of the character, because our scripts are mostly similar. But for some reason I don’t think that’s how it should be done and it didn’t work for me too (I tried to put Debug.Log(“Stopped moving”); in the part after “if (active == 0)” and during testing it never appeared in console/enemy was still moving/aiming at player during it’s attacks).
Then I tried to add a bool method StopMovement that checks if the isAttacking is true and if it’s true - transform.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
The whole method was looking like that:
public bool StoppingMovement()
{
if (isAttacking == true)
{
transform.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
return (true);
}
else
{
return (false);
}
}
But because my knowledge of C# is pretty much lacking during my attempts to make it work I was getting different errors like “Cannot implicitly convert type ‘void’ to ‘bool’” or “Method must have a return type” and after spending a whole evening of googling I was never able to make it work. Can
someone please explain how should I create a boolean method, check if “isAttacking” state is “true” right now and, if it is, stop movement/rotating of the enemy?
Thank you very much in advance!