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!!!!!

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

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.


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