I’m working from the book Unity 5.x Game Development Blueprints and I’m on the Mobile Endless Game (aka Flappy Bird clone). I’m receiving a Warning message and an Error message in Unity about my Rigidbody2D object. Not really sure what’s going on since the code I’m using seems to be correct according to the other posts I’ve found. I’m also having trouble with getting the .AddForce() to work - this is probably because the Rigidbody2D isn’t working.
**Here’s the messages I’m getting: **
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//[RequireComponent (typeof(Rigidbody2D))]
public class PlayerBehavior : MonoBehaviour {
[Tooltip("The force which is added when the player jumps")]
public Vector2 jumpForce = new Vector2(0, 300);
// If we've been hit, we can no longer jump
private bool beenHit;
private Rigidbody rigidbody2D;
// Use this for initialization
void Start () {
beenHit = false;
rigidbody2D = GetComponent<Rigidbody2D> ();
}
// Will ne called after all of the Update functions
void LastUpdate () {
// Check if we should jump as long as we haven't been hit yet
//if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0) && !beenHit) {
if (Input.GetKeyDown(KeyCode.Space)) {
Debug.Log ("jump!");
// Reset velocity and then jump
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.AddForce (jumpForce);
}
}
// If we collide with any ofthe polygon colliders then we crash
// other: what we collided with
void OnCollisionEnter2D (Collision2D other) {
// We have now been hit
beenHit = true;
// The animation should no longer play, so we can set the speed to 0 or destroy it
GetComponent<Animator>().speed = 0.0f;
}
}