0
votes

I'm making a game where the character is continuously jumping up and down. I use OnCollisionEnter() to make him jump every time he hits the ground. I am trying to invoke an animation that make the characters arms wiggle inside the function as well, like this:

void OnCollisionEnter(Collision collision){

    foreach(ContactPoint contact in collision.contacts){
        rigidbody.velocity = transform.up*10;
        audio.Play();
        animation.Play ("JumpAnimation");
    }
}

When I run the game I get the following error:

MissingComponentException: There is no 'Animation' attached to the "Green Bot" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Green Bot". Or your script needs to check if the component is attached before using it.

I have an animator component attached to my "Green Bot" and the animation plays if I click Loop, but I only want it to play inside the above function. How can I check if the component is attached inside the script, as the error suggests?

UPDATE:

I've set my code to:

void OnCollisionEnter(Collision collision){

    foreach(ContactPoint contact in collision.contacts){
        rigidbody.velocity = transform.up*10;
        audio.Play();
        animator.SetTrigger("Jump");
    }
}

and here is a snapshot of my Animator window:

enter image description here

2

2 Answers

1
votes

Have you considered the using a trigger within the animator and then calling animator.SetTrigger("YourTrigger") within your OnCollisionEnter event? Within the animator you would create the aforementioned trigger parameter (boolean) and tie your animation to that.

void OnCollisionEnter(Collision collision){

  foreach(ContactPoint contact in collision.contacts){
    rigidbody.velocity = transform.up*10;
    audio.Play();
    animator.SetTrigger("Jump");
  }
}

The Unity3D Tutorials on Animator Scripting may also be a helpful reference for you as they walk through this concept in more detail including how to properly configure the animator.

1
votes

You should have an animation component in addition to animator if you want to use animation. Play then in "size" part of animation, enter 1 and press enter. An input comes. Select your animation, that's it.

Enjoy!