What is wrong with this script?

Hi, guys. I was watching a tutorial, where it’s been said that to destroy an instance of a prefab (which is instantiated in another script named ProjectileScript.js) 5 seconds after it’s hit something you need to attach this script to your prefab:

#pragma strict

function Start () {

}

function Update () {

}
  
function OnCollisionEnter (collision : Collision){
Destroy(gameObject,5);
}

But it has returned this error:
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.

So after a lot of googling I wrote/copypasted this script:

#pragma strict

var targetScript;
var targetObj: Transform; 

function Start () {

}

function Update () {

}
  
function OnCollisionEnter (collision : Collision){
var targetScript: ProjectileScript = targetObj.GetComponent(ProjectileScript);
Destroy(targetScript.instance,5);
print(collision.transform.name);
}

The question is: was the first script supposed to work and destroy only one instance, but not the whole object, or maybe it was possible only in previous versions of Unity?

Thanks for help!

These

Destroy(gameObject,5);
Destroy(targetScript.instance,5);

are only equivalent if the Game Object that the script is attached to is also the Game Object that targetScript.instance is attached to.

If you destroy a Game Object, you can’t reference it anymore.

Your first script if is attached to your prefab (which you want to destroy) is working only at the time you instatiate the prefab from your ProjectileScript.
The error you have means that the script on prefab (the one you are showing us) is working perfect but the other script (ProjectileScript : you are not showing us) is trying to do something with this prefab (which is destroyed).
Find what is that or give us and the other script so we can have a better “look” to can help you…