Problem with animation 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.
(Door script)
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;
}
}
}
Answer by Ledifen · Aug 13, 2017 at 10:30 AM
Okay. So I'm really not experienced but as I had trouble starting an animation on certain condition and I found a solution, I might be able to help you out. I answered that on my own question with a step by step explanation here. It's not the same situation, but the principle might work.
Basically, you could go into your animator window and add a boolean parameter and use it as a condition to play your animation. (This I what I explain in the 7 steps on my question).
When it comes to your code, I'm going to try something but... well, I'm not experienced.
public Animator animatorDoor; //The animator component that holds the door animation
void Start () {
animatorDoor.enabled = true;
animatorDoor.SetBool("canOpenDoor", false); // set the boolean you created as a condition to false so the animation doesn't play
}
void OpenTheDoor() {
animatorDoor.SetBool("canOpenDoor", true); // create a function that change the boolean value and so plays the animation
}
void Update() {
if (blah blah your conditions blah blah) {
OpenTheDoor();
}
}
So... Is it working ?
Hahah, I'm really not sure ^^'
Anyway, good luck with that.