-1

i'm trying to make a game on unity using C# for a games dev course. the course is: https://www.youtube.com/watch?v=b8YUfee_pzc and at 51:55 is where i am experiencing the error. the error is NullReferenceException: Object reference not set to an instance of an object player.FixedUpdate () (at Assets/scripts/player.cs:32) i have checked and it seems to be letter by letter (including caps) perfect, unless i'm jsut stupid. it may be because of outdated code, something in unity or me just copying something down wrong. anyhow, here's the code:

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

[RequireComponent(typeof(BoxCollider2D))]
public class player : MonoBehaviour
{

    private BoxCollider2D boxCollider;
    private RaycastHit2D hit;
    private Vector3 moveDelta;

    private void start(){
        boxCollider = GetComponent<BoxCollider2D>();
    }

    private void FixedUpdate()
    {
       float x = Input.GetAxisRaw("Horizontal");
       float y = Input.GetAxisRaw("Vertical");

        // reset move delta
       moveDelta = new Vector3(x, y, 0);

        // swap sprite direction
        if(moveDelta.x > 0)
            transform.localScale = Vector3.one;
        
        else if (moveDelta.x < 0)
            transform.localScale = new Vector3(-1,1,1);

            hit =  Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(0, moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("actor", "blocking"));
            if (hit.collider == null)
            {
             transform.Translate(0, moveDelta.y * Time.deltaTime, 0);    
            }

            hit =  Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x, 0), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("actor", "blocking"));
            if (hit.collider == null)
            {
             transform.Translate( moveDelta.x * Time.deltaTime, 0, 0);    
            }
    
    }
   
    

}```


Wfar
  • 3
  • 1
  • Have you put a breakpoint on the line in question? put each object in to the watch window. My guess would be the boxcollider2d doesn't exist on the gameobject. – Monofuse Mar 14 '22 at 19:24
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – BugFinder Mar 14 '22 at 21:04

1 Answers1

0

Found a comment on that video that worked for me: "changing "private BoxCollider2D boxCollider;" to "public BoxCollider2D boxCollider;" then dragging the box collider in to the tab on the script under your npc"