The object of type 'GameObject' has been destroyed but you are still trying to access it. Your scrip

I currently faced this problem where what I do makes this error. “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.” Code is
```csharp
**using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mining : MonoBehaviour
{
public double Health = 10;

public GameObject XO;


void Start()
{
    XO = GameObject.FindWithTag("rawOre");
}

void OnTriggerEnter2D(Collider2D col)
{
    if(col.gameObject.tag == "Player")
    {
        damage();
    }
}

void damage()
{
    Health -= 2.5;
}

void Spawn()
{
    Instantiate(XO, transform.position, Quaternion.identity);
}

void Update()
{
    if(Health <= 0)
    {
        Spawn();
        Destroy(gameObject);
    }
}

}**
** **and this is the second one that error happened because of** **csharp
**using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class oreCollectable : MonoBehaviour
{
public GameObject rawOre;

public Text Amount1;
public Text Amount2;

public bool Statment = false;

private Transform target;

private float spead = 5.0f;

public int ItemAmount = 0;
public int ItemAmount2 = 0;

void Start()
{
    target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}

void Update()
{
    transform.position = Vector2.MoveTowards(transform.position, target.position, spead * Time.deltaTime);
}

private void OnTriggerEnter2D(Collider2D col)
{
    if(col.gameObject.tag == "Player")
    {
        ItemAmount++;
        string AI = ItemAmount++.ToString();
        Amount1.text = AI;
        Destroy(rawOre);
    }
}

}**
```
Can Someone help, It would be great if yes.

It’s hard to explain that error any better. The trick is you have to figure out which line specifically above is still trying to do something with an already-Destroyed object. Here’s a useful way to do that:

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

Does the error state what line of code it’s happening at?

Is it possible your OnTriggerEnter2d is being called twice somehow?

I think I know the issue but I don’t know how to solve it. The issue is that I’m accessing the gameObject’s script that it’s gameObject was destroyed. So I’m thinking that maybe I can change the script position from that gameObject to another Empty GameObject. Maybe you can have other solutions to that issue. And Actually the game object is being cloned(Instantiated) so maybe that would change something.

oooh, yeah it is saying line 33 and 40. But I don’t know how to make that issue disapear. And new issue happened. "
The Object you want to instantiate is null.
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <42a5878ce129403083acccf18e43363f>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <42a5878ce129403083acccf18e43363f>:0)
Mining.Spawn () (at Assets/Mining.cs:33)
Mining.Update () (at Assets/Mining.cs:40)
"

Those line numbers don’t match up with either of the code segments you’ve posted above, and by the error log you’ve put there it potentially corresponds to the mining script, while the initial error I was referring to was in the ‘oreCollectable’ script, was it not? It would be helpful if you point us to the lines of code that are actually causing the error by using Inline Code tags.

As for your new error, it’s because your ‘XO’ field (terrible variable name, sorry) is exactly what it says, null. So either your Start callback isn’t finding anything, or you have multiple objects with the “rawOre” tag and once you destroy the one that corresponds with the tag, then it will be null.

To reiterate Kurt, please use Debug.Log statements to see how your code is executing. As I said previously, is your OnTriggerEnter2D being called twice? You can determine this in 2 seconds with some Debug.Log statements. If not, what else is trying to access your game object after it’s been destroyed already? This is also easily determined with more Debug.Log statements.

No it’s only showing at Mining script,
“Mining.Spawn () (at Assets/Mining.cs:33)Mining.Update () (at Assets/Mining.cs:40).” And the lines are ```

  • void Spawn()
  • {
  • Instantiate(XO, transform.position, Quaternion.identity);
  • }

and

  • void Update()
  • {
  • if(Health <= 0)
  • {
  • Spawn();
  • Destroy(gameObject);
  • }
  • }

[quote="spiney199, post:6, topic: 861448, username:spiney199"]
you have multiple objects with the "rawOre" tag and once you destroy the one that corresponds with the tag, then it will be null.
[/quote]
Yes, I have a lot of clones that have "rawOre" tag. 

[quote="spiney199, post:6, topic: 861448, username:spiney199"]
To reiterate Kurt, please use Debug.Log statements to see how your code is executing. As I said previously, is your OnTriggerEnter2D being called twice? You can determine this in 2 seconds with some Debug.Log statements. If not, what else is trying to access your game object after it's been destroyed already? This is also easily determined with more Debug.Log statements.
[/quote]
No, it's not because of that. I did one thing and that issue disappeared however new issue came, "The Object you want to instantiate is null." and the lines are those two problematic ones" Mining.Spawn () (at Assets/Mining.cs:33)
Mining.Update () (at Assets/Mining.cs:40)".
(Thank you for still continuing to help me.)