transform.parent not working? (Unity 2d)
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;
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.name == "Player1")
{
transform.parent = coll.gameObject.transform;
}
if (coll.gameObject.name == "Player2")
{
transform.parent = coll.gameObject.transform;
}
}
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)
Answer by tormentoarmagedoom · May 20, 2019 at 09:47 AM
Hello.
First, I supose its nothing, and works anyway, but i can not check it now, anfi always use "gameObject" to be sure:
transform.parent.gameObject.tag == ....
Now, lets see. You are getting nullreference, Are you sure is in the if condition line? did you debugged the code line by line while running? Sometimes (i dnt know when exatcly or why) the error seems to be in the if condition, but actually is inside if { }, and as the if can not be solved, it seems the null in isn the condition, but not, is inside the if.
TO be sure, do this and check the result:
private void Update()
{
Debug.Log (transform.parent.gameObject.tag);
if (transform.parent != null && transform.parent.tag == "Player1")
{
........
We will see if the problem is that parent. But i think its not, i think the problem is inside the if. DEbugg the code and find what cariable is still null.