Search Unity

How to null check?

Discussion in 'Editor & General Support' started by rolltide101x, Feb 16, 2020.

  1. rolltide101x

    rolltide101x

    Joined:
    Jan 23, 2020
    Posts:
    1
    I am working to remake PvZ in Unity for practice and I believe I am getting this error because I am not null checking line 33 but I can not figure out how to nullcheck it.


    I am getting this error in Unity

    "NullReferenceException: Object reference not set to an instance of an object
    Peashooter.FireBullet () (at Assets/Scripts/Peashooter.cs:33)"


    I am sure this is a simple solution that I am looking over on Google but I appreciate any help. Thanks!

    Code (CSharp):
    1. private void FireBullet()
    2.     {
    3.        if (Mathf.Abs(transform.position.x - FindObjectOfType<Zombie>().transform.position.x) < RangeToShoot)
    4.         {
    5.            
    6.             RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, Vector2.right * 12);
    7.             Debug.Log("Print!");
    8.  
    9.            
    10.  
    11.                 foreach (RaycastHit2D hit in hits)
    12.                 {
    13.                     if (hit.collider != null &&
    14.                         hit.collider.gameObject.tag == "Zombie")
    15.  
    16.                     {
    17.                         Instantiate(Bullet,
    18.                           FirePoint.transform.position,
    19.                             Quaternion.identity);
    20.                     }
    21.  
    22.                 }
    23.              }
    24.     }
     

    Attached Files: