transform.parent.tag not working?
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)
Answer by $$anonymous$$ · Oct 08, 2019 at 07:26 PM
@acuaro transform.parent
is null
.
But if parent is null, when checking
if (transform.parent != null && ....)
just should skip the if.
@acuaro CAn you add this line just before that if?
Debug.Log (transform.parent);
So you can check at the consolo the value of parent all frames.
Your answer
Follow this Question
Related Questions
transform.parent not working? (Unity 2d) 1 Answer
Setting parent through custom script not working. 0 Answers
how add child to multi gameobject 0 Answers