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.
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:
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.