- Home /
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)
collectedItem would just be a boolean that is initially false, and you would set it to true when the player picks up the item. Once it becomes true, the timer would start counting until it reaches it's limit and respawns the item.
I could not figure out how to make your way work but I did figure out how to make the object spawn after a certain amount of time.
Glad you got it working, maybe post your new code as an answer in case someone else has a similar problem?
Answer by straydogstrut · Apr 10, 2010 at 05:40 PM
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;
}
}
how do I make it so that the object does not appear until a set time?
Answer by HardStyle · Apr 30, 2012 at 07:40 PM
is better to just hide the object or something like that..
Your answer
Follow this Question
Related Questions
How to correctly convert Object to GameObject 1 Answer
Switching Gameobjects in a variable 1 Answer
Need help with logic problem (JavaScript) 1 Answer
Non-hard-coded object reference? 2 Answers