Squiddu
Squiddu

Reputation: 29

Unity2D - Player not moving no matter what I try

I've been trying to get the new input system for Unity2D working, but I've been struggling; despite looking through multiple tutorials, even if I manage to get rid of all errors, I simply don't move.

Now, whenever I run the scene, I get flooded with this error over and over again:

NullReferenceException: Object reference not set to an instance of an object PlayerM.Update () (at Assets/PlayerM.cs:27)

Here's my player movement script:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerM : MonoBehaviour
{

    Rigidbody2D rb;
    Vector2 pos;
    public float speed = 2f;

    void Start()
    {

    }

    void OnMove(InputValue value)
    {
        pos = value.Get<Vector2>();
        Debug.Log("Moving!");
    }

    // Update is called once per frame
    void Update()
    {
        rb.MovePosition(rb.position + pos * speed * Time.deltaTime);
    }    
}

And here's my input action asset:

I've attempted switching between 2D and 1D axis to no avail.

Upvotes: 0

Views: 129

Answers (1)

person132
person132

Reputation: 111

To set the rigidbody to the attached component rather than null, try adding the line

rb = GetComponent<RigidBody>();

to your Start() method.

Upvotes: 1

Related Questions