0
\$\begingroup\$

I have created a simple game and there are zombies as my enemies.If the distance of The player(Which is me) and the zombie less than 10,The zombie starts walking towards me.and there is a Cylinder object around me.I have turned off the Mesh Renderer of that cylinder so that it is invisible. And also there is a mesh collider in the Cylinder. If the zombie reaches the cylinder , it starts to attack me and stops walking.But walking animation is still working.

How can I fix this, I need to stop walking animation of the zombie when it reaches the cylinder.Here is my code,

using UnityEngine;
using System.Collections;

public class ZombieFollow : MonoBehaviour
{

    public GameObject ThePlayer;
    public float TargetDistance;
    public float AllowedRange = 10;
    public GameObject TheEnemy;
    public float EnemySpeed;
    public int AttackTrigger;
    public RaycastHit Shot;

    void Update()
    {
        transform.LookAt(ThePlayer.transform);
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
        {
            TargetDistance = Shot.distance;
            if (TargetDistance < AllowedRange)
            {
                EnemySpeed = 0.01f;
                if (AttackTrigger == 0)
                {
                    TheEnemy.GetComponent<Animation>().Play("Walking");
                    transform.position = Vector3.MoveTowards(transform.position, ThePlayer.transform.position, EnemySpeed);
                }
            }
            else
            {
                EnemySpeed = 0;
                TheEnemy.GetComponent<Animation>().Play("Idle");
            }
        }

        if (AttackTrigger == 1)
        {
            EnemySpeed = 0;
            TheEnemy.GetComponent<Animation>().Play("Attacking");
        }
    }

    void OnTriggerEnter()
    {
        AttackTrigger = 1;
    }

    void OnTriggerExit()
    {
        AttackTrigger = 0;
    }

}

Here ThePlayer Gameobject is me and TheEnemy is the zombie.Walking, Idle and Attacking are the animations.

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Why use animation.play??

Why don't you use transition to animation, add parameters and play your animation according to the parameters? It's much smoother that way

Never the least you could try animation.stop()

\$\endgroup\$
0
\$\begingroup\$

Is the zombie colliding with the trigger? If it isn't registering the collision then it will never change the attack value.

Another user also posted about using animation transitions. In unity you can set up a kind of state machine in the animator component and control that with variables. It will be cleaner and more optimized than calling PlayAnimation in Update.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .