<aside> 📄 This script triggers an animation when the designated component ontriggerenters. You will need to designate the animator, the animation trigger (parameter in animator) and target (player or other gameobject).
</aside>
using UnityEngine;
public class OnTriggerAnimation : MonoBehaviour
{
public Animator animator;
public string triggerName = "YourAnimationTrigger";
public string targetTag = "Player"; // Change this to the desired target tag
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag(targetTag))
{
// Player (or target with the specified tag) entered the trigger zone, trigger the animation
TriggerAnimation();
}
}
private void TriggerAnimation()
{
// Trigger the animation by setting the specified trigger parameter
animator.SetTrigger(triggerName);
}
}
For Animation On and Off when Exiting the Trigger Zone
using UnityEngine;
public class OnTriggerAnimation : MonoBehaviour
{
public Animator animator;
public string triggerName = "YourAnimationTrigger";
public string stopTriggerName = "StopAnimationTrigger"; // Trigger to stop/reset animation
public string targetTag = "Player"; // Change this to the desired target tag
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag(targetTag))
{
// Player (or target with the specified tag) entered the trigger zone, trigger the animation
TriggerAnimation();
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag(targetTag))
{
// Player (or target with the specified tag) exited the trigger zone, stop/reset the animation
StopAnimation();
}
}
private void TriggerAnimation()
{
// Trigger the animation by setting the specified trigger parameter
animator.SetTrigger(triggerName);
}
private void StopAnimation()
{
// Stop the animation by setting the stop trigger parameter
animator.SetTrigger(stopTriggerName);
}
}