How to set Animation to Looping via script?

Yo im trying to loop an animation only if certain condition are set. But this just changes the state of animation, it doesn’t play the animation back.

public Animator anim;
private void PlayAgain()
{
anim.Play("myAnim");
}

I also tried switching to idle briefly and setting it back to my animation (shooting) but it doesn’t work since its on the same frame it just stays on the shooting state and stays on the last frame.

How do I set an animation to loop at runtime?
OR
How do I play an animation back while being in the same animation state?

Thanks

Hi @KitingMechanics ,

This code is working fine for me. Somehow I needed to set 2 more curves for the y and z axes despite I just want to move the GameObject on the x-axis. (Is it a unity bug or a feature? :D)

public class MoveAnimation : MonoBehaviour
{
    private Animation animation;

    void Start()
    {
        Vector3 startPos = transform.localPosition;
        AnimationCurve translateX =
            AnimationCurve.Linear(0.0f, startPos.x, 2.0f, startPos.x + 1);
        AnimationCurve translateY =
            AnimationCurve.Linear(0.0f, startPos.y, 2.0f, startPos.y);
        AnimationCurve translateZ =
            AnimationCurve.Linear(0.0f, startPos.z, 2.0f, startPos.z);

        AnimationClip clip = new AnimationClip();
        clip.legacy = true; // make the clip to be playable by script
        clip.SetCurve("", typeof(Transform), "localPosition.x", translateX);
        clip.SetCurve("", typeof(Transform), "localPosition.y", translateY);
        clip.SetCurve("", typeof(Transform), "localPosition.z", translateZ);
        clip.wrapMode = WrapMode.PingPong; // loop forward-backward forever!

        animation = GetComponent<Animation>();
        animation.AddClip(clip, "test");
        animation.Play("test");
    }
}