I have a health GameObject that has a chance to get instantiated when destroying an enemy. Most of the time, it heals the player, plays the sound effect, etc. In other words, it behaves the way it is supposed to. However, sometimes (maybe 1 out of 10 times) when running into the instantiated object, it will play the sound effect but will not heal the player and it will not get destroyed. The error that accompanies this is:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.bindings.cs:211) UnityEngine.Object.Instantiate[GameObject] (UnityEngine.GameObject original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.bindings.cs:285) Heart.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/Heart.cs:36)
I've been trying to figure out for quite some time what is happening and I can't seem to pinpoint the issue. Under the health up object where the error is pointing to is (error is actually pointing to the line where the tempPickupEffect is getting instantiated):
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.name == "Player_Ship")
{
AudioSource.PlayClipAtPoint(receiveSound, Camera.main.transform.position, 0.5f);
GameObject tempPickupEffect = Instantiate(pickupEffect, transform.position, transform.rotation) as GameObject;
tempPickupEffect.GetComponent<ParticleSystem>().Play();
Destroy(tempPickupEffect, 3f);
heal = true;
Level1.playerHealth += healAmount;
Destroy(gameObject);
}
}
Under my enemy script, I have a method named spawnHealthUp() being called when the enemy's health is at or below zero. This is the method:
private void spawnHealthUp()
{
chance = Random.value;
if (chance <= healthSpawnChance)
{
GameObject copyHealthUp = Instantiate(healthUp, transform.position, Quaternion.identity) as GameObject;
copyHealthUp.GetComponent<Rigidbody2D>().velocity = new Vector2(-healthSpeed, 0f);
}
}
Thank you in advance for any insight into this anyone can offer.