- Home /
The question is answered
Inconsistent script results/error
Hi there,
I'm working on a simple health script for my game. It should be simple- if the object in which healthscript.cs is attached gets hit by a player bullet, it takes damage. When its HP = 0, it should return to the pool (a.k.a. be destroyed).
It seems like the script works every 2 out of 10 times: The bullet hits the enemy, which is destroyed and returned to the pool. All the other times, the enemy absorbs bullets like a sponge and the console throws this error every time the shot hits:
NullReferenceException: Object reference not set to an instance of an object healthscript.OnTriggerEnter2D (UnityEngine.Collider2D otherCollider) (at Assets/Scripts/healthscript.cs:22)
Here is my health script, where the magic (and errors) happen:
using UnityEngine;
using System.Collections;
public class healthscript : MonoBehaviour
{
public int health = 1;
public bool isEnemy = true;
public void Damage (int damageCount)
{
health -= damageCount;
if (health <= 0) {
GameObject obj = explodepool.current.GetPooledObject ();
obj.transform.position = transform.position;
obj.transform.rotation = transform.rotation;
obj.SetActive (true);
gameObject.SetActive (false);
}
}
void OnTriggerEnter2D (Collider2D otherCollider)
{
playerbulletscript shot = otherCollider.gameObject.GetComponent<playerbulletscript> ();
if (shot != null) {
if (shot.isEnemyShot != isEnemy) {
Damage (shot.damage);
}
}
}
}
Is it possible that you are destroying the shot when it enters the Trigger in another place? If this is the case the otherCollider could be null because the GameObject it belongs to got destroyed.
Unless you're using DestroyImmediate I would guess that Unity sometimes destroys the GameObject of the shot before the TriggerEnter gets called and sometimes afterwards. Which would explain the random behaviour you are experiencing.
If this is the case then a solution would be to destroy your shots on the next Frame and not on the current.
Answer by PlayKiseki · Oct 07, 2014 at 11:57 PM
Hi KayelGee,
I figured out what the issue was. There were two scripts destroying the object at once, caused my bulletscript to try and deactivate itself after it had been activated. Thanks anyway!
Follow this Question
Related Questions
2.5D Shmup, how to create bullets on "camera plane"? 0 Answers
Health System Raycast Bullets 2 Answers
bullets that do damage 1 Answer
Making an HUD 3 Answers