NullReferenceException: Object reference not set to an instance of an object

Hi guys, i’ve got a question.

I made a mini “game” just to test some stuff out. I wanted my character to shoot bombs that explode into particles on impact with the ground. But everytime the bomb hits the ground one particle is created and i get the Error message : NullReferenceException: Object reference not set to an instance of an object.

Here my code:

First PlayerControll.cs:

public class PlayerControll : MonoBehaviour
{

    public Animator animator;

    public Transform trsnGun;
    public Transform muzzle;

    public float moveSpeed;

    public Vector2 groundDispenseVelocity;
    public Vector2 verticalDispenseVelocity;

    public Rigidbody2D rb;

    public GameObject bulletPreFab;

    private Vector2 moveDirection;
    private Vector2 mousePos;
   

    void FixedUpdate()
    {
        Move();
        ProcessInputs();
        RotateGun();
        Shoot();
    }


    void ProcessInputs()
    {

        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");

        moveDirection = new Vector2(moveX, moveY).normalized;

        if (moveDirection != Vector2.zero)
        {
            animator.SetFloat("Horizontal", moveX);
        }

        animator.SetFloat("Speed", moveDirection.sqrMagnitude);
    }

    void Move()
    {
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
    }

    void RotateGun()
    {
        mousePos = Input.mousePosition;

        Vector3 objectPos = Camera.main.WorldToScreenPoint(trsnGun.position);
        mousePos.x = mousePos.x - objectPos.x;
        mousePos.y = mousePos.y - objectPos.y;

        float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
        trsnGun.rotation = Quaternion.Euler(0f, 0f, angle);

        if (angle < -90 || angle > 90)

        {
            if (trsnGun.eulerAngles.y == 0)
            {
                trsnGun.localRotation = Quaternion.Euler(180, 0, -angle);
            }

            else if (trsnGun.eulerAngles.y == 180)
            {
                trsnGun.localRotation = Quaternion.Euler(180, 180, -angle);
            }
        }
    }

    void Shoot()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject tempFab = Instantiate(bulletPreFab, muzzle.position, Quaternion.identity);
            tempFab.GetComponent<FakeHeight>().Initialize(trsnGun.right * Random.Range(groundDispenseVelocity.x, groundDispenseVelocity.y), Random.Range(verticalDispenseVelocity.x , verticalDispenseVelocity.y));
        }
    }
}

Second one FakeHeight.cs:

public class FakeHeight : MonoBehaviour
{
    public UnityEvent groundHitEvent;

    public GameObject bullet;

    public Transform trnsObject;
    public Transform trnsBody;
    public Transform trnsShadow;

    public Vector2 groundVelocity;

    public float verticalVelocity;
    public float gravity = -10;

    public bool isGrounded;

    // Update is called once per frame
    private void FixedUpdate()
    {
        UpdatePosition();
        CheckTouchdown();
    }

    public void Initialize(Vector2 groundVelocity, float verticalVelocity)
    {
        this.groundVelocity = groundVelocity;
        this.verticalVelocity = verticalVelocity;
    }

    void UpdatePosition()
    {
        if (!isGrounded)
        {
            verticalVelocity += gravity * Time.deltaTime;
            trnsBody.position += new Vector3(0, verticalVelocity, 0) * Time.deltaTime;
        }

        trnsObject.position += (Vector3)groundVelocity * Time.deltaTime;
    }

    void CheckTouchdown()
    {
        if (trnsBody.position.y < trnsObject.position.y && !isGrounded)
        {
            isGrounded = true;
            trnsBody.position = trnsObject.position;
            GroundHit();
        }


    }

    void GroundHit()
    {
        groundHitEvent.Invoke();
    }

    public void Remove()
    {
        Destroy(bullet);
    }
}

and the last one with the error DebrisDispenser.cs:

public class DebrisDispenser : MonoBehaviour
{

    public GameObject debrisParticle;

    public Vector2 debrisGroundVelocityRange;
    public Vector2 debrisVerticalVelocityRange;
    public Vector2 debrisParticleSizeRange;
    public Vector2Int debrisAmountRange;

    public void DispenseDebris()
    {

        int debrisAmount = Random.Range(debrisAmountRange.x, debrisAmountRange.y);


        for (int i = 0; i < debrisAmount; i++)
        {
            GameObject particle = Instantiate(debrisParticle, transform.position, Quaternion.identity);
            if (particle != null)
            {
                particle.transform.localScale = Vector3.one * Random.Range(debrisParticleSizeRange.x, debrisParticleSizeRange.y);  // <-- works fine here
                particle.GetComponent<FakeHeight>().Initialize(Random.insideUnitCircle * Random.Range(debrisGroundVelocityRange.x, debrisGroundVelocityRange.y), Random.Range(debrisVerticalVelocityRange.x, debrisVerticalVelocityRange.y)); // NullReferenceException
            }
        }
    }
}

I have watched some videos and read some posts about this Error but i just can’t fix it. Maybe some of you can help. Thanks in advance.

you didnt post the full error

if you double click the error it sends you to the spot in your code that is bugged

My Bad sry it’s this part: (Line 23 in DebrisDispenser.cs)

Edit:

I forgot to add the pictures lmao

The game pretty much looks like this a small 8 bit guy that shoots bombs out of his canon. The bombs get thrown in an arc and when they hit the ground they should “explode” into particles or debris.

7126640--851330--Example1.jpg

The circled square is the only particle that gets created but it doesn’t even move and the other arrows show what should be happening with other particles that get created. (Bomb should disapear but i disabled it to find the Bug)

7126640--851333--Expample2.png

My initial guess is that you are destroying the object with the FakeHeight script on it so after it collides or lands, the entire object with the script is being destroyed so it cannot do the line with the error: particle.GetComponent()…

Well guys i found the problem. It was like Cornysam said that the particle got deletet before it could do stuff. The FakeHeight class has a boolean isGrounded() that checks if the shadow and body touch each other. When grounded is true it activates an event (in this example it destroys the GameObject). When the particle was created isGrounded() was already true because of the bomb so i changed the boolean to start as false. The second mistake was my prefab for the particle i should have used a similar design like the bomb (Body and Shadow) when i changed it it worked! thanks for the help

1 Like