- Home /
C# | How to detect the end of an animation?
Right, so I have 2 animations for a gun aiming. When I right click, the sights of the gun line up, and in the script the bool "gunAiming" becomes true. When it becomes true, and I right click again, the animation of the gun returning to it's original spot must be played and the bool will become false again. But the problem is that only the return animation is playing, and not the first aiming animation. Now, I think the problem is that the bool "gunAiming" becomes true immediately after pressing right-mouse button. So I think that the solution would be for the bool to become true once it detects that the animation ended. If that is not the problem, please provide another solution. Also, an in-depth explanation of what is happening in the script would be helpful. Here is the script:
public bool gunAiming = false;
void Update () {
if (Input.GetKey (KeyCode.Mouse1) && !gunAiming) {
GetComponent<Animation>().Play ("aim");
gunAiming = true;
}
if (Input.GetKey (KeyCode.Mouse1) && gunAiming) {
GetComponent<Animation> ().Play ("returnaim");
gunAiming = false;
}
}
Add an AnimationEvent to the clip that calls a function which sets the gunAi$$anonymous$$g bool to true or false.
You could do it like:
public bool gunAi$$anonymous$$g = false;
public Animation anim;
void Start() {
anim = GetComponent<Animation>();
}
void Update () {
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.$$anonymous$$ouse1)) {
if (!anim.IsPlaying("aim")) {
anim.Play ("aim");
}
if (!gunAi$$anonymous$$g) {
gunAi$$anonymous$$g = true;
// Also can do some stuff
}
} else {
if (!anim.IsPlaying("mouseOverEffect")) {
anim.Play ("returnaim");
}
if (gunAi$$anonymous$$g) {
gunAi$$anonymous$$g = false;
// Also can do some stuff
}
}
}
Answer by gaming_man_is_gaming · Apr 13, 2021 at 12:40 PM
not sure if this fixes it but where it says Input.GetKey you have to put at the end .down. so it would be
if (Input.GetKeyDown(KeyCode.Mouse1) && !gunAiming) {
GetComponent<Animation>().Play ("aim");
gunAiming = true;
then Input.GetKeyUp() for second one. But i wouldnt use animations in general because it can be unreliable. instead i would put a game object in front of your camera then one at the unaimed state. then create a script to set the position of the gun to that the game object infront of your camera then when not aiming in go back to the unaimed state. if you need help with the script just reply to my answer and ill put it in
Thank you for your response! Hahaha! After five years, you have answered my question. This project is unfortunately no more, though I will accept your answer.
well im just glad it helped