How to respawn a game object after a certain amount of time.

I am making a game using javascript. I was wondering how to make a game object respawn after a certain amount of time. the idea is the character collects the object and then after about 20 seconds the object respawns at the same point. The character can then collect the object again.

My original script is the following: private var timeSinceLastCollision = 0;

function OnControllerColliderHit(hit:ControllerColliderHit){

    if(hit.gameObject.tag == "PowerUp(smaller)" && timeSinceLastCollision <= 0) 
    {
        Destroy(hit.gameObject);
        transform.localScale = Vector3(transform.localScale.x * .5, transform.localScale.y * .5, transform.localScale.z * .5);
        timeSinceLastCollision = 5;
        //Wait at least 5 seconds between collisions
    }
    timeSinceLastCollision -= Time.deltaTime;    
}

so where do I put the script you wrote and what do I put in the spot where you wrote (collecteditem)

The Robot Guards of the 3D Platformer Tutorial on the Unity website respawn when the player can no longer see them. They are Instantiated from a prefab on this line:

currentEnemy = Instantiate(enemyPrefab, transform.position, transform.rotation);

Have a look at the tutorial I've linked to above and instantiating prefabs in the Unity Manual.


To respawn the item after a certain amount of time, you could start a timer once the player collects the object. Once the timer reaches the time limit you have specified, you can then respawn the object. Something like the following in your Update function:

if(collectedItem){      
    respawnTimer += Time.deltaTime;
    if(respawnTimer > delayTime){
        var newObject = Instantiate(objectPrefab, transform.position,
        transform.rotation);
        respawnTimer = 0.0;
    }
}

is better to just hide the object or something like that…