1
\$\begingroup\$
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    public CharacterController2D controller;

    public float runSpeed = 40f;

    private float horizontalMove = 0f;

    // Update is called once per frame
    void Update () {
        horizontalMove = Input.GetAxisRaw("Horizontal")*runSpeed;
    }

    void FixedUpdate(){
        controller.Move(horizontalMove*Time.fixedDeltaTime,false,false);//error is somewhere here
    }
}

Though all the classes are defines it throws the error please help!!!!!

\$\endgroup\$
2
  • \$\begingroup\$ In this case, I would expect error to be caused because "controller" is null(unassigned). \$\endgroup\$
    – Nick
    Commented Oct 2, 2018 at 11:34
  • \$\begingroup\$ No @Nick i have assigned a controller in the inspector \$\endgroup\$
    – Parth Pant
    Commented Oct 2, 2018 at 11:56

1 Answer 1

1
\$\begingroup\$

Ensure you've assigned a valid component into your controller field in the inspector before running your game.

If you've looked and you're sure it's there, then you might accidentally have another instance of this PlayerMovement script somewhere else in your scene. Add a Debug.Log to print out the name of the object in Start() to help track down the spare, uninitialized instance.

Also, note that capturing horizontal input in Update(), saving it to a variable then using it in the next FixedUpdate() will add at least one unnecessary frame of latency to your input, since Update() runs after FixedUpdate() in a frame. Instead, you can read and use your axis input in FixedUpdate() directly to get the latest info "hot off the presses." ;)

I've seen advice claiming that the latest input isn't available until Update(), but experimentally this is not true for any version of Unity I've tested. It might be superstition left over from an older version, or an over-application of the rule to not naively handle instantaneous inputs (eg. button down events that happen for only one frame) in FixedUpdate() since it can miss or double-handle them. This is easy to work around though, so lag is usually unnecessary there too.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .