Hey anyone know how to fix this error ‘NullReferenceException: Object reference not set to an instance of an object’
Here is my script, any help is appreciated:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private LayerMask platformLayerMask;
public Rigidbody2D rb;
float moveLeft = -2000f;
float moveRight = 2000f;
float jumpForce = 10f;
private BoxCollider2D boxCollider2D;
void Start()
{
rb.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if(IsGrounded() && Input.GetKeyDown(KeyCode.W))
{
rb.velocity = Vector2.up * jumpForce;
}
}
public bool IsGrounded ()
{
float extraHeightTest = 1f;
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, extraHeightTest, platformLayerMask);
Color rayColor;
if (raycastHit.collider != null)
{
rayColor = Color.green;
}
else {
rayColor = Color.red;
}
Debug.DrawRay(boxCollider2D.bounds.center, Vector2.down * (boxCollider2D.bounds.extents.y + extraHeightTest));
Debug.Log(raycastHit.collider);
return raycastHit.collider != null;
}
void FixedUpdate ()
{
float xdirection = Input.GetAxisRaw("Horizontal");
float ydirection = Input.GetAxisRaw("Vertical");
if(xdirection == -1)
{
rb.AddForce(new Vector2(moveLeft * Time.deltaTime, 0f));
}
else if (xdirection == 1)
{
rb.AddForce(new Vector2(moveRight * Time.deltaTime, 0f));
}
}
}