- Home /
Moving an object forward, killing the object and respawning a new one.
So i have made a extremly simple pice of code, i do not know alot about coding.
var speed : float = 2.0;
function Update() {
transform.position += Time.deltaTime * speed * transform.forward;
}
This makes my object move forward from where its at and i can choose what speed it has. How do i make it die after x seconds and then making it respawn? Do i use a forloop or something? I dont know how to write a code for a loop so i need some help.
thanks in advance
Answer by aldonaletto · Oct 28, 2011 at 10:02 AM
That's not a loop case: you should have a timer variable; set it to 0 at the beginning and increment it each Update, comparing to the end time; when the time is reached, destroy the object and instantiate it at the start position, or just "teleport" it back to the beginning and zero the timer variable to restart the whole thing - something like this:
var speed : float = 2.0; var timer : float = 0; var endTime : float = 5; var initialPos : Vector3;
function Start(){ initialPos = transform.position; }
function Update() {
transform.position += Time.deltaTime * speed * transform.forward;
timer += Time.deltaTime;
if (timer >= endTime){
// it's easier to just move it to the beginning:
transform.position = initialPos;
// reset timer:
timer = 0;
}
} To kill and respawn the object, you should have another script to control the process or do a "clone-and-suicide" thing like this:
... if (timer >= endTime){ Instantiate(transform, initialPos, transform.rotation); Destroy(gameObject); } }This would destroy the variables too, but the brand new object would born with timer zeroed, since that's how we're initializing the variable.
The first alternative is preferred, since the second would create and delete memory blocks, what would expend time in the garbage collection, an internal house cleaning operation that recycle the deleted memory.
I was going to do something like a raycast perhaps, but this was much easyer
Your answer
Follow this Question
Related Questions
player not moving after respawn(java script) 1 Answer
Limit Diagonal Speed 2 Answers
DastardlyBanana(moving while jumping. 2 Answers
Rigidbody on a platform 2 Answers
How to make move up text Animimation when Button click? 0 Answers