transform.parent not working i keep getting this error NullReferenceException: Object reference not set to an instance of an object LaserWeapon.Update () (at Assets/SCRIPTS/LaserWeapon.cs:38)

In my game you can pick up a weapon like a laser sniper. I made the laser sniper but the problem is when i put in this line of code if (transform.parent != null && transform.parent.tag == “Player1”) and inside put my firing function so the player can only shoot the weapon once they got it in there hands. The firing function worked without that "if " function and i don’t know whats wrong heres my script for the laser sniper thx if you could help :D.

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

public class LaserWeapon : MonoBehaviour
{
public GameObject projectile;
public Transform shotPoint;

 private float timeBtwShots;
 public float startTimeBtwShots;






 // Start is called before the first frame update
 void OnCollisionEnter2D(Collision2D coll)
 {
     if (coll.gameObject.name == "Player1")
     {
         transform.parent = coll.gameObject.transform;

     }
     if (coll.gameObject.name == "Player2")
     {
         transform.parent = coll.gameObject.transform;
     }
 }

 // Update is called once per frame
 private void Update()
 {



     if (transform.parent != null && transform.parent.tag == "Player1") // ****NOT WORKING****
     {
         if (timeBtwShots <= 0)
         {
             if (Input.GetKeyDown(KeyCode.F))
             {
                 Instantiate(projectile, shotPoint.position, transform.rotation);
                 timeBtwShots = startTimeBtwShots;
             }
             else
             {
                 timeBtwShots -= Time.deltaTime;
             }
         }

     }



 }

}

Here is the error i’m getting NullReferenceException: Object reference not set to an instance of an object LaserWeapon.Update () (at Assets/SCRIPTS/LaserWeapon.cs:38)

Add comment