Search code examples
c#unity-game-enginecontrollerjoystick

Why do I get this error for a joystick in Unity?


I'm currently making a 2D game as a beginner and I wanted to add joystick controls to my game. I made everything like in the youtube video of Brackeys, but I always get this error:

NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:21)

Could anyone help me pls? The link to the youtube video and timestamp is:

https://youtu.be/bp2PiFC9sSs?t=780

my current script:

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

public class PlayerMovement : MonoBehaviour {

    public CharacterController2D controller;
    public Animator animator;

    public Joystick joystick;

    public float runSpeed = 40f;

    float horizontalMove = 0f;
    bool jump = false;
    bool crouch = false;

    // Update is called once per frame
    void Update() {

        if (joystick.Horizontal >= .2f)
        {
            horizontalMove = runSpeed;
        } else if (joystick.Horizontal <= -.2f)
        {
            horizontalMove = -runSpeed;
        } else
        {
            horizontalMove = 0f;
        }

        float verticalMove = joystick.Vertical;

        animator.SetFloat("Speed", Mathf.Abs(horizontalMove));

        if (verticalMove >= .5f)
        {
            jump = true;
            animator.SetBool("IsJumping", true);
        }

        if (verticalMove <= -.5f)
        {
            crouch = true;
        }
        else
        {
            crouch = false;
        }

    }

    public void OnLanding ()
    {
        animator.SetBool("IsJumping", false);
    }

    public void OnCrouching (bool isCrouching)
    {
        animator.SetBool("IsCrouching", isCrouching);
    }

    void FixedUpdate ()
    {
        // Move our character
        controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
        jump = false;
    }
}

Solution

  • Based on the video, you have to drag and drop the FixedJoystick object from the scene's hierarchy onto the PlayerMovement's joystick field in the Inspector (check out 11:24 from the video)