r/UnityHelp • • Aug 07 '21

UNITY Check for null on collider?

I have an object that shoots bullets, those bullets makes this error when they collide whit a clone of themselve.

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

BulletShot.OnTriggerEnter (UnityEngine.Collider collision_Unit) (at Assets/Prefabs/BulletShot.cs:43)

This comes up because the bullet doesn't have a parent. But as far as i understand it shouldn't be a problem since i tjek if there is a parent in line 43 with != null.

So how do i make sure that the if statement triggers the right way?

And yes i am completely new :D

​ <using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class BulletShot : MonoBehaviour {

public float damage;

public float speed;

public float deathTimer;

public string enemyTag;

private Vector2 EnemyPosition;

private Vector2 MyPosition;

public float m_Angle;

public Transform Owner;

public float poisonDamage;

public float poisonTimeInteval;

public float poisonTotalTime;

//public Target health;

private void Start()

{

}

private void Update()

{

transform.Translate(Vector3.forward * speed * Time.deltaTime);

Destroy(gameObject, deathTimer);

}

public void OnTriggerEnter(Collider collision_Unit)

{

if (collision_Unit.tag == "Enemy")

{

collision_Unit.gameObject.GetComponent<HealthScript>().TakeDamage(damage);

Destroy(gameObject);

}

else if (collision_Unit.transform.parent.gameObject != null && collision_Unit.transform.parent.gameObject == Owner.gameObject)

{

//if (collision_Unit.transform.parent.gameObject == Owner.gameObject)

//{

Debug.Log("Hallo");

//}

}

else if (collision_Unit.tag != "Spell")

{

Destroy(gameObject);

Debug.Log("non spell random obejct");

}

}

}>

3 Upvotes

4 comments sorted by

1

u/Bonejob Code Guru Aug 07 '21

The problem is you are not checking the parent first. It is evaluating the tag == "Enemy" first and then blowing up. I can't actually tell what is causing the Ref Object Error. Which line is line 43?

2

u/Qulddell Aug 07 '21

This is line 43

else if (collision_Unit.transform.parent.gameObject != null && collision_Unit.transform.parent.gameObject == Owner.gameObject)

If I remove this if statement no error occurs but the shoot stops at the sender collier sphere.

I really appreciates the help so thanks :)

2

u/Asylation Helped Community Aug 07 '21

collision_Unit.transform.parent is null already. By trying to access its gameObject with collision_Unit.transform.parent.gameObject it throws the NullReferenceException error.

1

u/Bonejob Code Guru Aug 07 '21

Will you edit your post and put it in a code block please. Select the code and press the "<>" button in the edit bar.