Animation is repeating - due to script logic

Hello all,

I’m writing a script for when the Avatar is approaching destination it plays “pick” animation (using mecanim).
I know that my logic is the problem, and I wonder if there’s a way to go around it.

    private void Reach()
    {
        shopper.meshRendererFlag.material.color = Color.yellow;
        shopper.animator.SetBool("Walk", false);
        shopper.animator.SetBool("Idle", true);
        PickupItem();
    }

    private void PickupItem()
    {
        if (shopper.navMeshAgent.remainingDistance <= shopper.navMeshAgent.stoppingDistance)
        {
            shopper.animator.SetTrigger("PickNeutral");
        }   
       shopper.StartCoroutine(ReachedTarget());
    }  

Of course the avatar is going to play the animation because the If statement remains true, as it’s stays at the same place until the next function, but how can it be fixed?

Thank you!

bool should_Play = true;

void PickupItem(){
if (shopper.navMeshAgent.remainingDistance <= shopper.navMeshAgent.stoppingDistance) {
		if (should_Play) {
			should_Play = false;
			shopper.animator.SetTrigger ("PickNeutral");
		}
	} else { 
		if (!should_Play)
			should_Play = true;
           }
   }  
}

The question is , how often is your PickupItem() function executed?

If it is executed more than once in a short time, The trigger will always be set. If the character enters the animation, the trigger may be reset, but it does not matter when you always set it. It means your Pickup animation will always repeat itself, because the trigger is always set to true.

Add a conditional logic that makes sure that PickupItem() can only be called once for an item that is on the ground (or whereever).

The PickupItem() function is executed each time the agent reaches the target.

There’s this function for animation:

 void Start(){
     animation.wrapMode = WrapMode.Once;
 }

But I need something like that for the animator.

I’ve implemented the code you’ve suggested with a little twist:

    private void PickupItem()
    {
        if (shopper.navMeshAgent.remainingDistance <= shopper.navMeshAgent.stoppingDistance)
        {
            if (playAnimation)
            {
                shopper.animator.SetTrigger("PickNeutral");
                playAnimation = false;
                shopper.StartCoroutine(ReachedTarget());
            } 
       }

      else if (!playAnimation)
            {
                shopper.StartCoroutine(ReachedTarget());
            }
        }   

But the next time I’m reaching the point the animation won’t play, so I’ve added the playAnimation = true; variable at the Coroutine.
Thank you for the code and for the guiding remarks!