How to fix "the object of type 'GameObject' has been destroyed, but you are still trying to access it" error in Unity?

TheBattleCat picture TheBattleCat · Feb 8, 2019 · Viewed 14.9k times · Source

I'm creating a 2.5D fighting game in Unity with C#. Currently, I'm trying to make a bumper appear around the player and disappear after a set amount of time. I've managed to make the bumper appear and disappear once, but after that, when I try to make the bumper appear again, Unity has an error for me: "The object of type 'GameObject' has been destroyed but you are still trying to access it."

I've tried using the "instantiate" and "destroy" commands, following a tutorial by "Brackeys" on 2D shooting. After also following some questions on forums about the same issue, I've altered my code again, but the problem persists.

The firePoint is an empty object, from where the BumperPrefab is instantiated.

using UnityEngine;

public class weapon: MonoBehaviour
{
    public Transform firePoint;
    public GameObject BumperPrefab;
    public float lifetime = 0.2f;

void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        attack();
    }

}
void attack()
{
    BumperPrefab = (GameObject) Instantiate(BumperPrefab, firePoint.position, firePoint.rotation);
    Destroy(BumperPrefab, lifetime);
}

}

I expect the GameObject "BumperPrefab" to appear, stick around for 0.2 seconds and disappear. I should be able to repeat that as many times as I want, but what actually happens is that I can do this only once and then the error "The object of type 'GameObject' has been destroyed but you are still trying to access it" shows up and I can't make the BumperPrefab appear again.

Any help is much appreciated!

Answer

Steven Coull picture Steven Coull · Feb 8, 2019
using UnityEngine;

public class weapon: MonoBehaviour
{
    public Transform firePoint;
    public GameObject BumperPrefab;
    public float lifetime = 0.2f;

void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        attack();
    }

}
void attack()
{
    var bumper = (GameObject) Instantiate(BumperPrefab, firePoint.position, firePoint.rotation);
    Destroy(bumper, lifetime);
}

Right now you're overwriting your public field containing the prefab object with your instantiated object, then destroying it. Set the instantiated object as a variable and you should be fine.