Create a prefab at same position where its destroyed

I am new to Unity3D gaming. I’ve an idea to create the same object/prefab at the same place where its being destroyed.
I wrote a script but doesn’t work for me.
var thePrefab : GameObject;
function Start (){
}
function Update (){
}

function OnTriggerEnter () {
    Destroy(gameObject);   
    yield WaitForSeconds (2);
    reGenerateTheCoin();
}
function reGenerateTheCoin ()
{
	Instantiate (thePrefab,transform.position,transform.rotation);
  	Debug.Log("Regenerated the Coin");
}

Thank you in Advance for your help.

If you destroy the object, you can’t reference its tranform, so save it in variables.

var thePrefab : GameObject;
private var oldPosition : Vector3;
private var oldRotation : Quaternion;

function Start (){ 
}

function Update (){ 
}

function OnTriggerEnter () {
    oldPosition = transform.position;
    oldRotation = transform.rotation;
    Destroy(gameObject);   
    yield WaitForSeconds (2);
    reGenerateTheCoin();
}
function reGenerateTheCoin ()
{
    Instantiate (thePrefab,oldPosition,oldRotation);
    Debug.Log("Regenerated the Coin");
}

This line:

Destroy(gameObject);

Will destroy your gameobject as well as your script. The coroutine will be destroyed as well since it’s running on your script which has been destroyed already. Also usually you can’t reference a prefab from a script that is part of the prefab (if i understood you right).

The problem is that references which reference other things inside the prefab are changed to the actual instantiated objects when the prefab is instantiated. So if a script on a prefab holds a reference to it’s own prefab, the reference would just reference the cloned object and not the prefab.

A solution which would fix both issues would be to use a second prefab with another simple script:

// HelperScript.js
var prefab : GameObject;
var waitTime = 2.0f;

function Start()
{
    yield WaitForSeconds(waitTime);
    Instantiate(prefab,transform.position, transform.rotation);
    Destroy(gameObject);
}

Create an empty GameObject, attach this script, assign the prefab you want to instantiate and turn that object also into a prefab called “Helper” for example.

Now the script on your original prefab wouldn’t reference it’s own prefab, but the Helper prefab. With this setup you would do this:

function OnTriggerEnter ()
{
    Instantiate (theHelperPrefab, transform.position, transform.rotation);
    Destroy(gameObject);
}

Now when you enter the trigger the helper prefab will be created and the object will be destroyed. After the set time (2 sec) the helper prefab will instantiate a new instance and destroy itself.

I think the best approach for this would actually be to set the game object to be inactive and then reactivate when the player collides with a trigger. I’m new to scripting in unity but im pretty sure the game object will not move after it is set inactive, that will make it to where you can “save” that game object’s position