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)
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.
Kurt made a fantastic sticks about fixing NullReferenceExceptions. It's literally always the same. Very useful if you get used to it quickly, it's really easy to fix once you did it once https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/