play animation on collision
I used this code but it doesen't work.
using UnityEngine;
public class PlayAnimOnTrigger : MonoBehaviour {
public Animator anim;
public AudioClip sound;
void Start () {
anim.enabled = false;
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == ("Player"))
{
anim.enabled = true;
AudioSource.PlayClipAtPoint(sound, transform.position);
}
}
}
Answer by MichaI · Jan 08, 2019 at 12:32 AM
Your code does't work because it sets animator disabled on start and enables it on first player's collision with trigger, it means that animator will play it's start animation and only once. To play animation on every collision you can create iddle animation as starting animation and use animator trigger to transit to animation you want play calling Animator.SetTrigger function. For more info check out:
-manual: https://docs.unity3d.com/Manual/class-AnimatorController.html ,
-video tutorial: https://unity3d.com/learn/tutorials/topics/animation/animator-controller ,
-documentation: https://docs.unity3d.com/ScriptReference/Animator.SetTrigger.html
Answer by alexxx9799 · Jan 08, 2019 at 12:47 AM
I need to play the animation only one time. But when the player collide the animation won't start.
If you are sure that trigger enables animator, than it has to be something wrong with your animator or animation itself (make sure that your animation is connected to entry box, and that your animation is not empty). You can try disabling animator already in edit mode, but this shouldn't change anything. If trigger doesn't play make sure that player collider has "Player" tag on itself.
there is something wrong with the code. the only thing that works is this: anim.enabled = false; because if I remove the code the animation start automatically. The problem is that the animation does not start if I hit the trigger.
Try make Debug.Log("Something"); right before anim.enabled = true; inside "if statement", if that doesn't log in console it means you have something wrong with colliders or tagging, in other case you can check if Start method is not called multiple times by some other instances of script by logging something from Start method. Also you can check if changing Start to Awake helps.
Your answer
![](https://koobas.hobune.stream/wayback/20220612185300im_/https://answers.unity.com/themes/thub/images/avi.jpg)