Search Unity

Bug Im stupid and need help

Discussion in 'Scripting' started by gerbyboss, Mar 30, 2023.

  1. gerbyboss

    gerbyboss

    Joined:
    Mar 30, 2023
    Posts:
    1
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Player : MonoBehaviour
    {
    private BoxCollider2D boxCollider;
    private Vector3 moveDelta;
    private RaycastHit2D hit;

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

    private void FixedUpdate()
    {

    float x = Input.GetAxisRaw("Horizontal");
    float y = Input.GetAxisRaw("Vertical");

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

    // Swap sprite direction, als je links of rechts gaat
    if (moveDelta.x > 0)
    transform.localScale = Vector3.one;
    else if (moveDelta.x < 0)
    transform.localScale = new Vector3(-1, 1, 1);

    //make sure we can move in this direction by checking for a hit box
    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)
    {
    //make this thing move
    transform.Translate(0, moveDelta.y * Time.deltaTime, 0);
    }

    hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x,0), Mathf.Abs(moveDelta.x * Time.deltaTime), LayerMask.GetMask("Actor", "Blocking"));
    if (hit.collider == null)
    {
    //make this thing move
    transform.Translate(0, moveDelta.x * Time.deltaTime, 0, 0);
    }
    }
    }




    if i add the boxcast it refuses to work. i do not understand

    error:
    NullReferenceException: Object reference not set to an instance of an object
    Player.FixedUpdate () (at Assets/Player.cs:32)
     
  2. karderos

    karderos

    Joined:
    Mar 28, 2023
    Posts:
    376
    did you add a box collider component to the same object where you put this script?
     
    Olipool likes this.
  3. midsummer

    midsummer

    Joined:
    Jan 12, 2017
    Posts:
    38
    Please use code tags when posting code in the forums, it's very hard to read otherwise.

    At a glance I noticed that there's a typo in the code. Start is supposed to be Start with an uppercase S. The method called "start" will never be called and boxCollider will always be null. The IDE you're using may even highlight the name of the function to tell you that it's a naming rule violation.

    Also, NullReferenceException is the error you will likely see most while working with C#. So learn what it means and you will always be able to fix it in your own code.
     
    Olipool likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,456
  5. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    midsummer and Kurt-Dekker like this.