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:
Full Robot script:
public class RobotController : MonoBehaviour
{
public float speed;
public float tiltX;
public float tiltY;
public float tiltZ;
Animator animator;
int jumpHash = Animator.StringToHash ("Jump");
void Start ()
{
animator = GetComponent<Animator>();
}
void FixedUpdate (){
Vector3 pos = transform.position;
pos.z = -2;
transform.position = pos;
Vector3 direction = Vector3.zero;
direction.x = -Input.acceleration.x*2f;
if ( direction.sqrMagnitude > 1 ){
direction.Normalize();
}
direction *= Time.deltaTime;
transform.Translate( direction * speed );
// Smoothes the rotation when touching Box collider... not sure why
rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}
void OnCollisionEnter(Collision collision){
foreach(ContactPoint contact in collision.contacts){
rigidbody.velocity = transform.up*10;
audio.Play();
animator.SetTrigger(jumpHash);
}
}
}
Animator window:
Inspector: