Can't call animation through script

Essentially, I am making a script that calls an animation whenever you are within certain distance of an object and hit a key. The game tells how close/far you are from the object using a raycast, which works fine and changes whenever you move. But then I get close to the door and hit E, nothing happens. I did a debug.log and the animation isn’t even called. I’d love to know what I am doing wrong here. Any help is appreciated. Door animation script is below, along with the raycast.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoorAnimation : MonoBehaviour {
    public Animator anim;
    public AudioSource dooropen;
    float TheDistance = PlayerRaycast.DistanceFromTarget;

    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator>();
    if (Input.GetButtonDown("Action")) {
        if (TheDistance <= 2) {
            OpenTheDoor();

        }
   
}
   
    }
   
    // Update is called once per frame
    void OpenTheDoor () {   
anim.GetComponent<Animator>().Play("Door001Anim", -1, 0);
        if(Input.GetButtonDown("Action"))
        { dooropen.Play();
         }

    }
}

(Raycast script)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlayerRaycast: MonoBehaviour {
public static float DistanceFromTarget;

public float ToTarget;


void  Update (){
    RaycastHit hit;
        if (Physics.Raycast (transform.position, transform.TransformDirection(Vector3.forward), out hit)) {
            ToTarget = hit.distance;
            DistanceFromTarget = ToTarget;       
        }
}

}

You’re retrieving the Animator component in your Start method, so there’s no need to call anim.GetComponent<Animator>() in your OpenTheDoor method. I would also use Input.GetButton("Action") instead.

Try:

void OpenTheDoor() {
    anim.Play("Door001Anim", -1, 0);
    if (Input.GetButton("Action")) {
        dooropen.Play();
    }
}
1 Like