Question by
R.E. Whaler Crozzan · Feb 06, 2016 at 11:56 AM ·
movement2d game2d-gameplay
2D Player Can't Move
Here is my code:
using UnityEngine;
using System.Collections;
public class Player_Movement : MonoBehaviour
{
Rigidbody2D RB2D;
Animator Anim;
// Use this for initialization
void Start ()
{
RB2D.GetComponent<Rigidbody2D> ();
Anim.GetComponent<Animator> ();
}
// Update is called once per frame
void Update ()
{
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector != Vector2.zero)
{
Anim.SetBool ("Is Walking", true);
Anim.SetFloat ("Input X", movement_vector.x);
Anim.SetFloat ("Input Y", movement_vector.y);
} else {
Anim.SetBool ("Is Walking", false);
}
RB2D.MovePosition (RB2D.position + movement_vector * Time.deltaTime);
}
}
Unity Version: 5.3.2f1
My player won't move when I press UP, DOWN, LEFT, RIGHT arrows and getting this error.
NullReferenceException: Object reference not set to an instance of an object Player_Movement.Start () (at Assets/Scripts/Player_Movement.cs:13)
NullReferenceException: Object reference not set to an instance of an object Player_Movement.Update () (at Assets/Scripts/Player_Movement.cs:28)
Comment
Best Answer
Answer by LazyElephant · Feb 06, 2016 at 02:29 PM
In your start function, you're not assigning your components properly. It should be
RB2D = GetComponent<Rigidbody2D> ();
Anim = GetComponent<Animator> ();