Home > Net >  Null referenced expectation error unity 2d player controller
Null referenced expectation error unity 2d player controller

Time:08-18

I am making this 2d platformer game where you play as a sprite that can jump and move right and left. I used the code from this video(Consle error

I don't know what to do with my code or character. all I can say is that it has a empty game object to tell when it touches the ground and has a 2d rigid body to it. here is my code

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

public class Ultranmove : MonoBehaviour
{
    private Rigidbody2D rb;
    public float speed;
    public float jumpForce;
    private float moveInput;

    private bool isGrounded;
    public Transform feetpos;
    public float checkRadius;
    public LayerMask WhatisGround;

    private float jumpTimeCounter;
    public float jumpTime;
    private bool isJumping;

    void start()
    {
        rb = GetComponent<Rigidbody2D>();


    }

    void FixedUpdate()
    {
        moveInput = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
    }
    void Update()
    {
        isGrounded = Physics2D.OverlapCircle(feetpos.position, checkRadius, WhatisGround);
        
        if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
        {
            isJumping = true;
            jumpTimeCounter = jumpTime;
            rb.velocity = Vector2.up * jumpForce;


        }
        if (Input.GetKey(KeyCode.Space) && isJumping == true)
        {
            if (jumpTimeCounter > 0)
            {
                rb.velocity = Vector2.up * jumpForce;
                jumpTimeCounter -= Time.deltaTime;
            }
            else
            {
                isJumping = false;

            }
            
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            isJumping = false;


        }
        
        if (moveInput > 0)
        {

            transform.eulerAngles = new Vector3(0, 0, 0);

        }
        else if (moveInput > 0)
        {

            transform.eulerAngles = new Vector3(0, 180, 0);

        }
    }



}
`

CodePudding user response:

You likely didn't reference your object in the inspector. See image

For me it's a float value but for you it would be a LayerMask or Transform. Try this depending on your situation.

CodePudding user response:

You have to attach a Rigidbody2D component to your player.

  • Related